/** * 主要wait方法需要同步锁住对象,如果锁不住的话,或抛出monitor异常,就是同步过程中 * 不是一个对象会造成这也的异常,例如线程的生产消费 所有锁住的对象都是obj上对于操作 * 我用自己的话来描述,如果你想看清楚的话, 你可以去看api 或者自己搜搜 * * @param args */ public static void main(String[] args) { Vector obj = new Vector<>(); Producer p = new Producer(obj); Thread thread = new Thread(p); Consumer c = new Consumer(obj); Thread thread1 = new Thread(c); thread.start(); thread1.start(); } static class Producer implements Runnable { Vector<Object> obj; public Producer(Vector<Object> obj) { this.obj = obj; } @Override public void run() { synchronized (obj) { while (true) { if (obj.size() != 0) { try { obj.wait(); System.out.println("running"); } catch (InterruptedException e) { e.printStackTrace(); } } obj.add("6666"); System.out.println("push"); obj.notify(); } } } } static class Consumer implements Runnable { Vector<Object> obj; public Consumer(Vector<Object> obj) { this.obj = obj; } @Override public void run() { synchronized (obj) { while (true) { if (obj.size() == 0) { try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } obj.clear(); System.out.println("take"); obj.notify();//通知生产者,通知之后消费者线程不会立即执行,因为obj.wait()没有释放对象锁, //so,你debug 消费者, 调用obj.wait()方法你会看到 生产这已经执行,如上日志 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
线程生产者与消费者
最新推荐文章于 2025-04-13 18:58:11 发布