六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 31|回复: 0

Java Thread (2)

[复制链接]

升级  36%

30

主题

30

主题

30

主题

秀才

Rank: 2

积分
104
 楼主| 发表于 2013-1-27 05:19:16 | 显示全部楼层 |阅读模式
1、让一个线程sleep有两种方法,一个是直接调用Thread.sleep(),另一个是使用枚举类型 java.util.concurrent.TimeUnit的枚举常量。
<div style="border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; background-color: rgb(238, 238, 238); font-size: 13px; width: 98%;">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();
    }
}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表