wait 释放锁 Posted on 2021-02-13 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667class ThreadB2 extends Thread { /** * 线程 BBB 持有对象锁 this,即当前对象 threadB2 */ @Override public void run() { synchronized (this) { System.out.println(Thread.currentThread().getName() + " beg " + System.currentTimeMillis()); System.out.println("B2 ing"); System.out.println(Thread.currentThread().getName() + " end " + System.currentTimeMillis()); } }}class ThreadA2 extends Thread { private ThreadB2 threadB2; public ThreadA2(ThreadB2 threadB2) { this.threadB2 = threadB2; } /** * 线程 AAA 持有对象锁 threadB2 */ @Override public void run() { //B2 被锁住 synchronized (threadB2) { System.out.println(Thread.currentThread().getName() + " beg " + System.currentTimeMillis()); try { System.out.println("wait之前:" + threadB2.isAlive()); threadB2.wait(); System.out.println("wait之后:" + threadB2.isAlive()); } catch (InterruptedException e) { e.printStackTrace(); }// try {// Thread.sleep(2000);// } catch (InterruptedException e) {// } System.out.println(Thread.currentThread().getName() + " end " + System.currentTimeMillis()); } }}class Run2 { public static void main(String[] args) { ThreadB2 threadB2 = new ThreadB2(); threadB2.setName("B2"); ThreadA2 threadA2 = new ThreadA2(threadB2); threadA2.setName("A2"); threadA2.start(); threadB2.start(); }} Donate comment here Donate WeChat Pay