sleep与wait
sleep是Thread方法,使得当前线程从运行态变为阻塞态。但它不会释放对象的锁。
wait方法是Object方法,它的作用是使得当前拥有对象锁的线程从运行态变为阻塞态,
它会释放对象的锁
sleep测试
package com.java.javabase.thread.sleep;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SleepTest {
private static int coutsize = 10;
private static Object obj = new Object();
public static void main(String[] args) {
Thread t1 =new ThreadOne("t1");
Thread t2 =new ThreadOne("t2");
t1.start();
t2.start();
}
static class ThreadOne extends Thread {
public ThreadOne(String name){
super(name);
}
@Override
public void run() {
synchronized (obj){
int i = 0;
try {
while (i < coutsize) {
log.info("current thread is : {} sleep {} times ",Thread.currentThread().getName(),i++);
Thread.sleep(300);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
说明
对于拥有同一个Object对象的两个线程,当一个线程持有对象的锁,虽然多次执行Thread,线程从运行态变为阻塞态,但也不会释放对象的锁,
其他的线程只能等待。
测试结果
2019-07-29 16:49:22,156 [t1] INFO SleepTest - current thread is : t1 sleep 0 times
2019-07-29 16:49:22,469 [t1] INFO SleepTest - current thread is : t1 sleep 1 times
2019-07-29 16:49:22,782 [t1] INFO SleepTest - current thread is : t1 sleep 2 times
2019-07-29 16:49:23,094 [t1] INFO SleepTest - current thread is : t1 sleep 3 times
2019-07-29 16:49:23,407 [t1] INFO SleepTest - current thread is : t1 sleep 4 times
2019-07-29 16:49:23,720 [t1] INFO SleepTest - current thread is : t1 sleep 5 times
2019-07-29 16:49:24,032 [t1] INFO SleepTest - current thread is : t1 sleep 6 times
2019-07-29 16:49:24,345 [t1] INFO SleepTest - current thread is : t1 sleep 7 times
2019-07-29 16:49:24,658 [t1] INFO SleepTest - current thread is : t1 sleep 8 times
2019-07-29 16:49:24,970 [t1] INFO SleepTest - current thread is : t1 sleep 9 times
2019-07-29 16:49:25,283 [t2] INFO SleepTest - current thread is : t2 sleep 0 times
2019-07-29 16:49:25,596 [t2] INFO SleepTest - current thread is : t2 sleep 1 times
2019-07-29 16:49:25,909 [t2] INFO SleepTest - current thread is : t2 sleep 2 times
2019-07-29 16:49:26,221 [t2] INFO SleepTest - current thread is : t2 sleep 3 times
2019-07-29 16:49:26,534 [t2] INFO SleepTest - current thread is : t2 sleep 4 times
2019-07-29 16:49:26,847 [t2] INFO SleepTest - current thread is : t2 sleep 5 times
2019-07-29 16:49:27,159 [t2] INFO SleepTest - current thread is : t2 sleep 6 times
2019-07-29 16:49:27,472 [t2] INFO SleepTest - current thread is : t2 sleep 7 times
2019-07-29 16:49:27,785 [t2] INFO SleepTest - current thread is : t2 sleep 8 times
2019-07-29 16:49:28,098 [t2] INFO SleepTest - current thread is : t2 sleep 9 times