`

Java Thread (2)

    博客分类:
  • Java
阅读更多
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、
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics