码迷,mamicode.com
首页 > 编程语言 > 详细

线程的休眠和中断

时间:2014-08-06 11:42:31      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:style   color   使用   io   for   art   ar   new   

在程序中允许一个线程进行暂时的休眠,直接使用Thread.sleep()方法即可实现休眠:

class myThread11 implements Runnable {
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(5000);
                System.out.println(Thread.currentThread().getName()
                        + " running " + i);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
}

public class ThreadSleepDemo {
    public static void main(String[] args) {
        myThread11 m = new myThread11();
        new Thread(m, "von‘s thread").start();
    }
}

 

当一个线程运行时,另外一个线程可以直接通过interrupt()方法中断其运行状态:

class myThread12 implements Runnable {
    public void run() {
        System.out.println("1,Begin run() method:");
        try {
            Thread.sleep(10000);
            System.out.println("2,Sleep have overd.");
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            System.out.println("3,Sleep be stoped.");
            return;
        }
        System.out.println("4,Stop run() method normally.");
    }
}

public class ThreadInteruptDemo {
    public static void main(String[] args) {
        myThread12 vMyThread = new myThread12();
        Thread thread = new Thread(vMyThread, "vThread");
        thread.start();
        try {
            thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        thread.interrupt();
    }
}

线程的休眠和中断,布布扣,bubuko.com

线程的休眠和中断

标签:style   color   使用   io   for   art   ar   new   

原文地址:http://www.cnblogs.com/vonk/p/3894083.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!