两个线程交替输出内容

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;
                }

            }
        }
    }
}

上一篇:同步工具类_Exchanger


下一篇:多线程之活锁(了解一下就可以了)