线程通信(交替执行)

package com.kaibing.thread;

/**
 * 线程的通信
 * <p>
 * wati()
 * notify():随机唤醒一个
 * notifyAll():全部唤醒
 */
class PrintNum implements Runnable {

    int num = 1;

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                notify();

                if (num <= 100) {
                    try {
                        Thread.currentThread().sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ":" + num);
                    num++;
                } else {
                    break;
                }

                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

public class Communication {

    public static void main(String[] args) {
        PrintNum p = new PrintNum();
        Thread t1 = new Thread(p);
        Thread t2 = new Thread(p);

        t1.setName("A");
        t2.setName("B");

        t1.start();
        t2.start();

    }
}

猜你喜欢

转载自www.cnblogs.com/kaibing/p/9233415.html