实现线程间的通信(一)

9 篇文章 0 订阅
4 篇文章 0 订阅
notify()和wait()实现:

this.notify():随机唤醒单个等待线程。

this.wait():当前线程等待,wait()若无人唤醒,则一直等待;而Thread.sleep是睡眠一定时间后再次启动。

 


public class DemoNotify {

    public static void main(String[] args) {
        final Print p=new Print();
        new Thread(){
            public void run(){
                while (true){
                    try {
                        p.print1();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        new Thread(){
            public void run(){
                while (true){
                    try {
                        p.print2();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
}
class Print{
    private int flag=1;
    public void print1() throws Exception{
        synchronized(this){
            if (flag!=1){
                this.wait();            //当前线程等待,wait()若无人唤醒,则一直等待;而Thread.sleep是睡眠一定时间后再次启动
                System.out.println("等待一");
            }
            System.out.print("1");
            System.out.print("2");
            System.out.print("3");
            System.out.print("4");
            System.out.println("5");
            flag=2;
            this.notify();          //随机唤醒单个等待线程
        }
    }
    public void print2() throws Exception{
        synchronized(this){
            if (flag!=2){
                this.wait();
                System.out.println("等待二");
            }
            System.out.print("上");
            System.out.print("山");
            System.out.print("打");
            System.out.print("老");
            System.out.println("虎");
            flag=1;
            this.notify();
        }
    }
}

运行结果:

12345
上山打老虎
等待一
12345
等待二
上山打老虎
等待一
12345
等待二
上山打老虎
等待一
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值