首页 > 编程语言 > 详细

线程通信(交替执行)

时间:2018-06-27 13:40:25      阅读:353      评论:0      收藏:0      [点我收藏+]
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();

    }
}

 

线程通信(交替执行)

原文:https://www.cnblogs.com/kaibing/p/9233415.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!