wait(timeout)
释放对象锁
import lombok.SneakyThrows;
public class T {
@SneakyThrows
public static void main(String[] args) {
Object o = new Object();
Thread thread1 = new Thread(() -> {
try {
synchronized (o) {
System.out.println(Thread.currentThread().getName() + "进入等待状态");
o.wait(5000);
System.out.println(Thread.currentThread().getName() + " over");
}
} catch (Exception e) {
e.printStackTrace();
}
}, "线程1");
Thread thread2 = new Thread(() -> {
synchronized (o) {
try {
System.out.println(Thread.currentThread().getName() + " hello");
} catch (Exception e) {
}
}
}, "线程2");
thread1.start();
thread2.start();
}
}
sleep()
不会释放对象锁
import lombok.SneakyThrows;
/*
线程1进入等待状态
线程1 over
线程2 hello
* */
public class T {
@SneakyThrows
public static void main(String[] args) {
Object o = new Object();
Thread thread1 = new Thread(() -> {
try {
synchronized (o) {
System.out.println(Thread.currentThread().getName() + "进入等待状态");
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName() + " over");
}
} catch (Exception e) {
e.printStackTrace();
}
}, "线程1");
Thread thread2 = new Thread(() -> {
synchronized (o) {
try {
System.out.println(Thread.currentThread().getName() + " hello");
} catch (Exception e) {
}
}
}, "线程2");
thread1.start();
thread2.start();
}
}
标签:currentThread,Thread,getName,System,vs,线程,sleep,out,wait
From: https://www.cnblogs.com/goodluckxiaotuanzi/p/18358552