juc相关知识
1、wait会释放锁,而sleep不会释放锁。
代码证明:
package com.xiangwen.day2;
public class DeadLockTest {
public static void main(String[] args) {
String a="aa";
String b="bb";
new Thread(new MyThread(a,b),"t1").start();
new Thread(new MyThread(b,a),"t2").start();
}
}
class MyThread implements Runnable{
private Object a;
private Object b;
public MyThread(Object a,Object b){
this.a=a;
this.b=b;
}
@Override
public void run() {
synchronized (a){
System.out.println("当前线程外"+Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if ("aa".equals(a)) {//t1是获取了aa的锁,t2是获取了bb的锁,现在t1wait,释放了aa的锁。t2可以跑完。
try {
a.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
synchronized (b){
System.out.println("当前线程里"+Thread.currentThread().getName());
}
}
}
运行截图