模拟抢购

package com.aaa.thread.Test;

public class Test1 implements Runnable {
    private int num=10;
    private int count=0;

    //必须使用start方法来进行run方法的运行
    @Override
    public void run() {
        while (true){
            if (!buy()){
                break;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //synchronized 不同步的
    public synchronized boolean buy(){
        if (num<=0){
            return false;
        }

        num--;
        count++;

        System.out.println(Thread.currentThread().getName() + "抢购到了衣服" + "还剩" + num + "");
        return true;
    }
//单线程安全无比
    public static void main(String[] args) {
        Test1 t = new Test1();
        Thread t1 = new Thread(t,"One");
        Thread t2 = new Thread(t,"Two");
        Thread t3 = new Thread(t,"Three");
        Thread t4 = new Thread(t,"Four");
        Thread t5 = new Thread(t,"Five");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();

    }
}

猜你喜欢

转载自www.cnblogs.com/fanqiexin/p/11124282.html