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:
- 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。
3、
分享到:
相关推荐
Java Thread用法 经典Java Thread用法 经典
2. 分析 Thread Dump,找到导致 CPU 高的线程 3. 分析线程的状态、锁信息、死锁信息等 4. 根据分析结果,定位性能瓶颈 在分析 Thread Dump 时,可以使用一些工具,例如 `jvis`、`VisualVM` 等。这些工具可以帮助...
JavaThread
Java Thread Programming by:Paul Hyde java 线程编程(包含代码)
为保证不会出现卖出同一个票数,要java多线程同步锁。 设计思路:1.创建一个站台类Station,继承Thread,重写run方法,在run方法里面执行售票操作!售票要使用同步锁:即有一个站台卖这张票时,其他站台要等这张票卖...
java线程分析工具
IBM关于java thread的教程 .pdf
Java-Thread-Affinity,将Java线程绑定到给定的内核.zip
java 應用 thread 的小程式 計算 time 的
Java Thread Dump Analyzing
Java线程(Java.Thread)(中英版).
各种 Java Thread State 第一分析法则
Java线程转储分析: 《Analyzing Java Thread Dumps.pdf》 《Java Thread Dumps 分析.pdf》
java.lang.Thread java.lang.Thread
java线程
Java Thread Programming (Sams) java线程编程,内含原代码,彩页,绝对写得精彩,看得舒服!
Java_Thread应该注意的问题
本文从JVM的角度探讨Java Thread的语法和编译结果,本文旨在介绍这些比较重要的线程相关的规范。
基于java的thread章节做的龟兔赛跑,是一个小游戏。
用java swing 做的贪吃蛇 这里只提供 src包的源文件,运行时请建立自己的工程,并将src下的所有包添加到你的工程的src目录下,运行在main包下的main类