用输入和输出两个线程对同一对象进行操作
1 package javase; 2 3 class Resource{ 4 String name; 5 String sex; 6 boolean flag; 7 } 8 9 class Output implements Runnable{ 10 11 Resource r; 12 public Output(Resource r) { 13 super(); 14 this.r = r; 15 } 16 17 @Override 18 public void run() { 19 20 r.flag = true; 21 while(true) { 22 23 synchronized (r) { 24 if(r.flag) { 25 System.out.println(r.name+"------"+r.sex); 26 r.flag = false; 27 r.notify(); 28 } 29 try { 30 r.wait(); 31 } catch (InterruptedException e) { 32 e.printStackTrace(); 33 } 34 35 } 36 } 37 38 } 39 40 } 41 42 class Input implements Runnable{ 43 44 private int x=0; 45 Resource r; 46 public Input(Resource r) { 47 super(); 48 this.r = r; 49 } 50 51 @Override 52 public void run() { 53 54 r.flag = false; 55 while(true) { 56 57 synchronized (r) { 58 if(r.flag) 59 try { 60 r.wait(); 61 } catch (InterruptedException e) { 62 e.printStackTrace(); 63 } 64 if(x%2==0) { 65 r.name = "佩奇"; 66 r.sex = "母猪"; 67 } 68 else { 69 r.name = "乔治"; 70 r.sex = "公猪"; 71 } 72 x++; 73 r.flag = true; 74 r.notify(); 75 } 76 77 } 78 79 } 80 81 } 82 83 public class ResourceDemo { 84 85 public static void main(String[] args) { 86 87 Resource r = new Resource(); 88 Input in = new Input(r); 89 Output out = new Output(r); 90 91 Thread t1 = new Thread(in); 92 Thread t2 = new Thread(out); 93 94 t1.start(); 95 t2.start(); 96 97 } 98 99 }
创建一个公用的对象给两个线程使用,一个为输入,一个为输出。当输入线程进入锁后会对对象元素进行赋值,唤醒锁对象线程池中的任意一个线程,然后使自己进入等待。此时输出线程拿到执行权,输出对象元素的值,再唤醒锁对象线程池中的任意一个线程,然后使自己进入等待。如此不断循环即可
原文地址:https://www.cnblogs.com/lsy-lsy/p/10921738.html
时间: 2024-11-05 15:58:18