1、让一个线程sleep有两种方法,一个是直接调用Thread.sleep(),另一个是使用枚举类型 java.util.concurrent.TimeUnit的枚举常量。

Clock.java
package sleep;
import static java.util.concurrent.TimeUnit.SECONDS; // utility class
public class Clock extends Thread
{
// This field is volatile because two different threads may access it
volatile boolean keepRunning = true;
public Clock()
{ // The constructor
setDaemon(true); // Daemon thread: interpreter can exit while it runs
}
public void run()
{ // The body of the thread
while (keepRunning)
{ // This thread runs until asked to stop
long now = System.currentTimeMillis(); // Get current time
System.out.printf("%tr%n", now); // Print it out
try
{
Thread.sleep(1000);
} // Wait 1000 milliseconds
catch (InterruptedException e)
{
return;
}// Quit on interrupt
}
}
// Ask the thread to stop running. An alternative to interrupt().
public void pleaseStop()
{
keepRunning = false;
}
// This method demonstrates how to use the Clock class
public static void main(String[] args)
{
Clock c = new Clock(); // Create a Clock thread
c.start(); // Start it
try
{
SECONDS.sleep(10);
} // Wait 10 seconds
catch (InterruptedException ignore)
{
} // Ignore interrupts
// Now stop the clock thread. We could also use c.interrupt()
c.pleaseStop();
}
}
2、守护进程daemon thread:
package sleep;
import static java.util.concurrent.TimeUnit.SECONDS; // utility class
public class Clock extends Thread
{
// This field is volatile because two different threads may access it
volatile boolean keepRunning = true;
public Clock()
{ // The constructor
setDaemon(true); // Daemon thread: interpreter can exit while it runs
}
public void run()
{ // The body of the thread
while (keepRunning)
{ // This thread runs until asked to stop
long now = System.currentTimeMillis(); // Get current time
System.out.printf("%tr%n", now); // Print it out
try
{
Thread.sleep(1000);
} // Wait 1000 milliseconds
catch (InterruptedException e)
{
return;
}// Quit on interrupt
}
}
// Ask the thread to stop running. An alternative to interrupt().
public void pleaseStop()
{
keepRunning = false;
}
// This method demonstrates how to use the Clock class
public static void main(String[] args)
{
Clock c = new Clock(); // Create a Clock thread
c.start(); // Start it
try
{
SECONDS.sleep(10);
} // Wait 10 seconds
catch (InterruptedException ignore)
{
} // Ignore interrupts
// Now stop the clock thread. We could also use c.interrupt()
c.pleaseStop();
}
}
2、守护进程daemon thread:
- Java 线程有两种类型,分别是 daemon thread 和 user thread
- daemon thread 的存在就是为了服务 user thread, 所以当JVM中所有的user thread线程都已经执行完毕时,JVM即将推出,因为此时 JVM 中剩下的 daemon 线程已经没有存在的必要了。
- 任何线程都可以是一个user thread 或者一个 daemon线程。可以调用方法 setDaemon(boolean isDaemon)来改变线程类型。需要注意的是,调用任何线程的该方法必须在该线程被start之前(例如在构造方法中),如果在线程running的时候调用该方法则会引发异常。
- 默认情况下,daemon thread 创建的线程是一个 daemon thread, user thread 创建的 thread是user thread。
本文介绍了Java中线程的两种睡眠方法及守护线程的概念。通过示例代码展示了如何使用Thread.sleep()方法使线程暂停执行,并解释了守护线程与用户线程的区别及其应用场景。

被折叠的 条评论
为什么被折叠?



