经典的消费者和生产者的关系
1.未使用线程同步的生产者消费者的关系
1)由于线程没有同步,消费者还没访问上一个数据,生产者就将新的数据写入了共享区,这可能导致数据丢失
表现为:
生产了8,9.而8丢失了
2)生产者生产下一个数据之前,消费者又访问了一次数据,这就可能导致数据重复。
变现为
代码为:
package thread; public class SharedCell { public static void main(String args[]) { HoldInteger h = new HoldInteger(); ProduceInteger p = new ProduceInteger(h); ConsumeInteger c = new ConsumeInteger(h); p.start(); c.start(); } } // 生产者进程 class ProduceInteger extends Thread { private HoldInteger pHold; public ProduceInteger(HoldInteger h) { pHold = h; } public void run() { for (int count = 0; count < 10; count++) { pHold.setSharedInt(count); System.out.println("Producer set sharedInt to " + count); try { sleep((int) Math.random() * 3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("Exception " + e.toString()); } } } } // 消费者进程 class ConsumeInteger extends Thread { private HoldInteger cHold; public ConsumeInteger(HoldInteger h) { cHold = h; } public void run() { int val; val = cHold.getSharedInt(); System.out.println("Consumer retrieved " + val); while (val != 9) { try { sleep((int) Math.random() * 3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("Exception " + e.toString()); } val = cHold.getSharedInt(); System.out.println("Consumer retrived " + val); } } } // 共享对象 class HoldInteger { private int sharedInt; public void setSharedInt(int val) { sharedInt = val; } public int getSharedInt() { return sharedInt; } }
结果: