码迷,mamicode.com
首页 > 编程语言 > 详细

线程通信(交替执行)

时间:2018-06-27 14:07:34      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:override   else   bing   cep   ble   zed   rgs   stat   print   

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();

    }
}

 

线程通信(交替执行)

标签:override   else   bing   cep   ble   zed   rgs   stat   print   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!