线程通信原理图:
- 资源类:
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(); } }
原文地址:https://www.cnblogs.com/tangshengwei/p/11735632.html
时间: 2024-10-09 02:36:05