其他分享
首页 > 其他分享> > 两个线程交替输出内容

两个线程交替输出内容

作者:互联网

public class App {

    public static void main(String[] args) throws Exception {
        sellTicket s = new sellTicket();
        Thread t1 = new Thread(s);
        Thread t2 = new Thread(s);
        t1.setName("t1");
        t2.setName("t2");
        t1.start();
        t2.start();
    }

}

class sellTicket implements Runnable {

    private int count = 1;

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                this.notify();
                if (count <= 100) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "购买了第" + count + "张票");
                   count++;
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }

            }
        }
    }
}

标签:输出,Thread,t2,t1,交替,sellTicket,线程,new,public
来源: https://blog.csdn.net/qq_26106607/article/details/122745060