版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chennai1101/article/details/84764558
1. Thread.sleep方法
sleep
方法挂起当前线程,直到一段时间后再次进入等待状态。
public class ThreadSleep extends Thread {
@Override
public void run() {
System.out.println("ThreadSleep begin " + System.currentTimeMillis());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println("ThreadSleep end " + System.currentTimeMillis());
}
public static void main(String[] args) {
new ThreadSleep().start();
}
}
输出
ThreadSleep begin 1543818092774
ThreadSleep end 1543818093774
2. sleep方法与锁对象
sleep()
方法并不会放弃锁对象。
public class ThreadSleepLock extends Thread {
Object lock;
public ThreadSleepLock(Object lock) {
this.lock = lock;
}
@Override
public void run() {
synchronized (lock) {
System.out.println("ThreadSleepLock begin " + System.currentTimeMillis());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println("ThreadSleepLock end " + System.currentTimeMillis());
}
}
public static void main(String[] args) {
Object lock = new Object();
new ThreadSleepLock(lock).start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
synchronized (lock) {
System.out.println("main end " + System.currentTimeMillis());
}
}
}
输出
ThreadSleepLock begin 1543818504341
ThreadSleepLock end 1543818506341
main end 1543818506341
3. sleep方法与interrupt方法
如果线程在挂起状态,调用线程的interrupt
方法会发生InterruptedException
异常。
public class ThreadSleepInterrupt extends Thread {
@Override
public void run() {
System.out.println("ThreadSleepInterrupt begin " + System.currentTimeMillis());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ThreadSleepInterrupt end " + System.currentTimeMillis());
}
public static void main(String[] args) {
Thread t = new ThreadSleepInterrupt();
t.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
t.interrupt();
}
}
输出
ThreadSleepInterrupt begin 1543818907713
java.lang.InterruptedException: sleep interrupted
ThreadSleepInterrupt end 1543818907814
at java.lang.Thread.sleep(Native Method)
at com.blog.demo.thread.ThreadSleepInterrupt.run(ThreadSleepInterrupt.java:9)
相关文章
Java Thread.join方法
Java Thread.sleep方法
Java Thread.Interrupt方法