其他分享
首页 > 其他分享> > 8、线程休眠

8、线程休眠

作者:互联网

8、线程休眠

 每个对象都有一把锁,sleep不会释放锁;

package com.testthread1;

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(500);
            } 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/16484542.html