黑马程序员_<<线程间通信>>
--------------------ASP.Net+Android+IOS开发、.Net培训、期待与您交流! --------------------
线程间通信:就是不同的线程共享同一资源,然后对资源进行不同的操作行为,说白了,在执行的线程运行代码是不一样的,但是代码中还含有共享资源。
2. 举例说明例如:例如就是有一资源(Res 煤),有两个线程分别执行的是赋值和取出(两辆卡车,一个是运来,一个是运走)
2. 举例
/*共享的资源*/public class Res { private String name; private String sex; private boolean flag = false;// 标志位,用来表示资源的状态/*同步函数赋值对象是 this*/ public synchronized void set(String name, String sex) {// 使用同步函数 if (flag) try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } this.name = name;//赋值 this.sex = sex; this.flag = true;//改变标识位 this.notify();//唤醒等待线程 }/*同步函数读取 对象是this*/ public synchronized void show() {// 同步函数 if (!flag) try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(this.name + ":" + this.sex);//读取 this.flag = false;//改变标识位 this.notify();//唤醒等待线程 }}/*输入类*/public class Input implements Runnable { private Res r = null;// 定义了一个资源 public Input(Res r) {// 通过构造方法初始化 this.r = r; } public void run() { int x = 0; while (true) { if (x == 0) { r.set("张三", "男"); } else { r.set("Joney", "female"); } x = (x + 1) % 2; } }}/*输出类*/public class Output implements Runnable { private Res r = null; public Output(Res r) {// 初始化资源 this.r = r; } public void run() { while (true) { r.show(); } } }/*测试类*/public class Text { public static void main(String[] agrs) { Res r = new Res(); new Thread(new Input(r)).start(); new Thread(new Output(r)).start(); }}
--------------------ASP.Net+Android+IOS开发、.Net培训、期待与您交流! --------------------