JAVA基础(多线程两个线程间的通信)

1,什么时候需要通信

  • 多个线程并发执行时, 在默认情况下CPU是随机切换线程的

  • 如果我们希望他们有规律的执行, 就可以使用通信, 例如每个线程执行一次打印

 

2,怎么通信

  • 如果希望线程等待, 就调用wait()

  • 如果希望唤醒等待的线程, 就调用notify();

  • 这两个方法必须在同步代码中执行, 并且使用同步锁对象来调用

 

3,案例

public class Demo1_Notify {





    /**

     * @param args

     * 等待唤醒机制

     */

    public static void main(String[] args) {

        final Printer p = new Printer();

        

        new Thread() {

            public void run() {

                while(true) {

                    try {

                        p.print1();

                    } catch (InterruptedException e) {

                        

                        e.printStackTrace();

                    }

                }

            }

        }.start();

        

        new Thread() {

            public void run() {

                while(true) {

                    try {

                        p.print2();

                    } catch (InterruptedException e) {

                        

                        e.printStackTrace();

                    }

                }

            }

        }.start();

    }





}





//等待唤醒机制

class Printer {

    private int flag = 1;

    public void print1() throws InterruptedException {                            

        synchronized(this) {

            if(flag != 1) {

                this.wait();                    //当前线程等待

            }

            System.out.print("我");

            System.out.print("是");

            System.out.print("小");

            System.out.print("帅");

            System.out.print("呀");

            System.out.print("\r\n");

            flag = 2;

            this.notify();                        //随机唤醒单个等待的线程

        }

    }

    

    public void print2() throws InterruptedException {

        synchronized(this) {

            if(flag != 2) {

                this.wait();

            }

            System.out.print("你");

            System.out.print("开");

            System.out.print("心");

            System.out.print("吗");

            System.out.print("\r\n");

            flag = 1;

            this.notify();

        }

    }

}





 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

兴帅_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值