`

thread-->demo6

阅读更多
package thread.demo;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/** 演示线程的睡眠时间,并且比较jdk 5与以前版本的不同 */
public class Demo6
{
    public static void main(String[] args)
    {
        ExecutorService service = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++)
        {
            service.execute(new Show(i));
        }
        service.shutdown();
    }
}

class Show implements Runnable
{
    private int name;
    
    public Show(int name)
    {
        this.name = name;
        
    }
    
    public void run()
    {
        Random ran = new Random();
        int i = ran.nextInt(9) + 1;
        try
        {
            TimeUnit.MILLISECONDS.sleep(i * 1000); // old style :Thread.sleep(100);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        System.out.println("线程" + name + "睡眠了" + i + "秒");
    }
    
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics