其他分享
首页 > 其他分享> > 3、并发问题

3、并发问题

作者:互联网

线程不安全

public class TestThread3 implements Runnable{

    private int ticketNums = 10 ;

    @Override
    public void run() {
        while (true){
            if (ticketNums==0){
                break;
            }
            System.out.println(Thread.currentThread().getName()+"拿到了"+ticketNums--+"票");
            //模拟延时
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        TestThread3 ticketThread = new TestThread3();

        //多线程操作同一个资源,线程不安全,数据乱
        new Thread(ticketThread,"liwang").start();
        new Thread(ticketThread,"dawang").start();
        new Thread(ticketThread,"ciwang").start();
        new Thread(ticketThread,"erwang").start();
    }
}

  

标签:TestThread3,Thread,start,问题,并发,ticketThread,new,public
来源: https://www.cnblogs.com/tfqfdr/p/16462837.html