package jack; public class ThreadA { private static Object lock = new Object(); private static Object lock1 = new Object(); public static void main(String[] args) { ThreadB threadB = new ThreadB(lock); threadB.start(); System.out.println("threadB is Start....."); synchronized (lock1) { ThreadC threadC = new ThreadC(lock); threadC.start(); /* try { */ System.out.println("Waiting for b to complete..."); /* threadB.wait(); */ /* * } catch (InterruptedException e) { // TODO Auto-generated catch * block } */ System.out.println("Total is :" + threadB.total); } } } class ThreadB extends Thread { Object object; ThreadB(Object object) { this.object=object; } int total = 0; public void run() { // TODO Auto-generated method stub synchronized (object) { System.out.println("ThreadB is running.."); for (int i = 0; i < 100; i++) { total += i; System.out.println("total is " + total); if (i == 50) { try { this.wait(); } catch (InterruptedException e) { } } try { Thread.sleep(30); } catch (InterruptedException e) { } } } } } class ThreadC extends Thread { Object obj = null; ThreadC(Object obj) { this.obj=obj; } int total = 0; public void run() { // TODO Auto-generated method stub synchronized (obj) { System.out.println("ThreadC is running.."); for (int i = 0; i < 100; i++) { total += i; System.out.println("TOTAL_C is " + total); try { Thread.sleep(30); } catch (InterruptedException e) { } } notify(); } } }
报错内容:
java.lang.IllegalMonitorStateException: current thread not owner
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Unknown Source)
at rendegen.ThreadB.run(ThreadA.java:55)