多线程-线程间通信-示例
1 package multithread4; 2 3 4 5 /* 6 * 线程间通讯: 7 * 多个线程在处理同一资源,但是任务却不同。 8 * 9 */ 10 11 //资源 12 class Resource{ 13 String name; 14 String sex; 15 } 16 17 //输入 18 class Input implements Runnable{ 19 Resource r; 20 // Object obj = new Object(); 21 public Input(Resource r) { 22 this.r = r; 23 } 24 public void run() { 25 int x = 0; 26 while(true) { 27 synchronized (r) { 28 if (x==0) { 29 r.name = "mike"; 30 r.sex = "nan"; 31 }else { 32 r.name = "丽丽"; 33 r.sex = "女女女"; 34 } 35 } 36 37 x = (x+1)%2; 38 } 39 } 40 } 41 42 //输出 43 class Output implements Runnable{ 44 Resource r; 45 public Output(Resource r) { 46 this.r = r; 47 } 48 public void run() { 49 while(true) { 50 synchronized (r) { 51 System.out.println(r.name+"....."+r.sex); 52 } 53 54 } 55 56 } 57 } 58 59 60 public class ResourceDemo { 61 62 public static void main(String[] args) { 63 //创建资源 64 Resource r = new Resource(); 65 //创建任务 66 Input in = new Input(r); 67 Output out = new Output(r); 68 //创建线程,执行路径 69 Thread t1 = new Thread(in); 70 Thread t2 = new Thread(out); 71 //开启线程 72 t1.start(); 73 t2.start(); 74 } 75 76 }