线程同步——产生负值

package thread;
/*
 * 线程同步
 * 线程安全
 */
public class ThreadSafeTest implements Runnable{
    int num=10;//设置当前总票数
    public static void main(String[] args) {
        ThreadSafeTest t= new ThreadSafeTest();//实例化类对象
        //以该类对象分别实例化4个线程
        Thread tA=new Thread(t);
        Thread tB=new Thread(t);
        Thread tC=new Thread(t);
        Thread tD=new Thread(t);
        //分别启动线程
        tA.start();
        tB.start();
        tC.start();
        tD.start();
    }
    @Override
    public void run() {
        while(true){
            if(num>0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("tickets"+num--);
            }
        }
        
    }

}



猜你喜欢

转载自blog.csdn.net/qq_41978199/article/details/80655852