线程的等待与唤醒,实现if...else里面的值交互依次输出
Posted tangshengwei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程的等待与唤醒,实现if...else里面的值交互依次输出相关的知识,希望对你有一定的参考价值。
线程通信原理图:
- 资源类:
package com.yonyou.sci.gateway.exec.threadnet; public class Resource { String name; String sex; // 用于表示赋值后的成员变量值有没有被输出 或 赋值成功 boolean flag = false; }
- 成员变量赋值类:
package com.yonyou.sci.gateway.exec.threadnet; public class Input implements Runnable { private Resource r; public Input (Resource r) { this.r = r; } @Override public void run () { int i = 0; while (true) { synchronized (r) { // 如果 flag 为 true 说明变量 name、sex 已经成功赋值,还没有被输出 if (r.flag) { try { r.wait(); }catch (Exception e){}; } else { if (i%2 == 0) { r.name = "张三"; r.sex = "男"; } else { r.name = "xiaohong"; r.sex = "girl"; } // 给变量 name、sex 赋值完成后,把 falg 标识更改为true r.flag = true; i++; // 唤醒线程 r.notify(); } } } } }
- 打印成员变量值:
package com.yonyou.sci.gateway.exec.threadnet; public class Output implements Runnable { private Resource r; public Output (Resource r) { this.r = r; } @Override public void run () { while (true){ synchronized (r){ // 如果 flag 为 false 说明变量 name、sex 没有被赋值,等待变量赋值 if (!r.flag) { try{ r.wait(); }catch (Exception e){ e.getMessage(); }; } else { System.out.println(r.name+"........"+r.sex); r.flag = false; r.notify(); } } } } }
- 启动线程类:
package com.yonyou.sci.gateway.exec.threadnet; public class mainResource { public static void main(String[] args) { Resource r = new Resource(); Input i = new Input(r); Output o = new Output(r); Thread t1 = new Thread(i); Thread t2 = new Thread(o); t1.start();t2.start(); } }
以上是关于线程的等待与唤醒,实现if...else里面的值交互依次输出的主要内容,如果未能解决你的问题,请参考以下文章
阶段1 语言基础+高级_1-3-Java语言高级_05-异常与多线程_第4节 等待唤醒机制_8_等待唤醒机制代码实现_包子类&包子铺类