java进程通信问题求助
程序代码:
package ThreadTest; import java.util.ArrayList; import java.util.List; public class FirstThread { static List<Object> goods = new ArrayList<>(); //储存物品的仓库,最多储存1 public static void main(String[] args) throws InterruptedException { Producer thread1 = new Producer(); Consumer thread2 = new Consumer(); Thread p1 = new Thread(thread1, "生产者1"); Thread p2 = new Thread(thread1, "生产者2"); Thread p3 = new Thread(thread1, "生产者3"); Thread c1 = new Thread(thread2, "消费者1"); Thread c2 = new Thread(thread2, "消费者2"); Thread c3 = new Thread(thread2, "消费者3"); p1.start(); p2.start(); p3.start(); c1.start(); c2.start(); c3.start(); } static class Producer implements Runnable { @Override public void run() { // TODO Auto-generated method stub int num = 0; while(true) { synchronized (goods) { if(goods.size()==0) { goods.add("商品" + ++num); System.out.println(Thread.currentThread().getName()+"生产了第"+num+"个产品"); } else if(goods.size()>0) try { goods.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } static class Consumer implements Runnable { @Override public void run() { // TODO Auto-generated method stub int num = 0; while(true) { synchronized (goods) { if(goods.size()>0) { goods.remove("商品"+ ++num); System.out.println(Thread.currentThread().getName()+"消费了第"+num+"个产品"); } else if (goods.size()==0) goods.notify();; } try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
为什么所有的生产者不是共用一个num,输出时每个生产者都会输出1,2...。我按照书上的例子可以实现共享,是不是这里是内部类的问题,但是如果不用内部类我又怎么实现生产者和消费者之间的通信呢,
顺便再问一个问题,那就是我按照书上的例子敲的,但是每次执行的结果都是几乎由一个窗口完成全部售票,没有达到上下两张票的窗口一定不同,代码如下:
按理来说sleep(100)会保证不让同一线程连续执行
程序代码:
package ThreadTest; class SaleThread2 implements Runnable { int tickets = 10; Object lock = new Object(); @Override public void run() { // TODO Auto-generated method stub while(true) { synchronized (lock) { if(tickets>0) { try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"正在出售第"+tickets-- +"张票"); } } } } } public class Example12 { public static void main(String[] args) { SaleThread2 st = new SaleThread2(); new Thread(st, "窗口1").start(); new Thread(st, "窗口2").start(); new Thread(st, "窗口3").start(); new Thread(st, "窗口4").start(); } }