wait和sleep区别
- sleep不会释放资源,wait会
- sleep必须传入等待时长
- wait和sleep都会让出cpu
工具类:
public class ThreadUtil {
public static void join(Thread ... ts) {
for(Thread t : ts) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void wait(Object lock) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void wait(long millis, Object lock) {
try {
lock.wait(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
测试程序
public class WaitAndSleepTest {
public static void main(String[] args) {
testRelease();
}
public static void testRelease() {
final Object lock = new Object();
new Thread(() -> {
synchronized (lock) {
System.out.println("a拿到锁");
ThreadUtil.sleep(3000);
System.out.println("a释放锁");
}
}).start();
new Thread(() -> {
ThreadUtil.sleep(500);
synchronized (lock) {
System.out.println("b拿到锁");
ThreadUtil.wait(1000, lock);
System.out.println("b释放锁");
}
}).start();
}
}
a拿到锁
a释放锁
b拿到锁
b释放锁
Process finished with exit code 0