两个线程,一个写入,一个读取:
package tst.thread;public class InputOutput { public static void main(String[] args) { Res r = new Res(); new Thread(new Input(r)).start(); new Thread(new Output(r)).start(); }}class Input implements Runnable { Res r; public Input(Res r) { this.r = r; } public void run() { int x = 0; while(true) { if(x == 0) { r.setInfo("小明", "男"); } else { r.setInfo("小红", "女"); } x = (x + 1) % 2; } }}class Output implements Runnable { Res r; public Output(Res r) { this.r = r; } public void run() { while(true) { r.showInfo(); } }}class Res { private String name; private String sex; boolean flag = false; public synchronized void setInfo(String name,String sex) { if(flag) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } this.name = name; this.sex = sex; flag = true; this.notify(); } public synchronized void showInfo() { if(!flag) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("The name is " + this.name + ",the sex is " + this.sex); flag = false; this.notify(); }}
当多线程是多个写入,多个读取,若按上述操作则可能出现所有线程同时等待。这时判断flag应该为while,而不用if,并改notify()为notifyall()!下为例子:
package tst.thread;public class ProCon { public static void main(String[] args) { Resource r = new Resource(); Pro p1 = new Pro(r); Pro p2 = new Pro(r); Cons p3 = new Cons(r); Cons p4 = new Cons(r); Thread t1 = new Thread(p1); Thread t2 = new Thread(p2); Thread t3 = new Thread(p3); Thread t4 = new Thread(p4); t1.start(); t2.start(); t3.start(); t4.start(); }}class Resource { private String proname = "Product--"; private int count = 0; private boolean flag = false; public synchronized void pro() { while(flag) { try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + "==" + proname + "生产---" + ++count); flag = true; this.notifyAll(); } public synchronized void con() { while(!flag) { try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + "==" + proname + "消费------" + count); flag = false; this.notifyAll(); }}class Pro implements Runnable { Resource r; public Pro(Resource r) { this.r = r; } public void run() { while(true) { r.pro(); } } }class Cons implements Runnable { Resource r; public Cons(Resource r) { this.r = r; } public void run() { while(true) { r.con(); } }}