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

线程控制

时间:2015-09-23 23:34:16      阅读:377      评论:0      收藏:0      [点我收藏+]

标签:

一、线程休眠

  使用的方法:public static void sleep(long millis):让正在执行的线程休眠millis毫秒

  public static void sleep(long millis , int nanos):让正在执行的线程休眠millis毫秒加nanos纳秒

public class Test implements Runnable{
    
    private String res = "test";
    public void run(){
        try {
            // 休眠1s
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.print(res);
    }
}

二、线程加入

  使用的方法:public void join():等待该线程终止

  当对线程对象调用此方法时,只有当该线程执行完毕后其他线程才可以执行。

public static void main(String[] args) {
        Test t = new Test();
        
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
        
        try {
            t1.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        t1.start();
        // t1执行完t2才执行
        t2.start();
    }

三、线程礼让

  使用的方法:public static void yield():暂停当前正在执行的线程,执行其他线程

public class Runable1Demo implements Runnable{

    public void run() {
        Thread.yield();
        System.out.println(Thread.currentThread().getName());
    }
    
}

四、守护线程

  使用的方法:public void setDaemon(boolean on):将该线程标记为守护线程或者是用户线程,on如果为true标记为守护线程。守护线程会在用户线程结束后被迫结束而不管有没有运行完,可以理解为守护线程守护服务于用户线程。

  

public static void main(String[] args) {
        Test t = new Test();
        
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
        
        t1.setDaemon(true);
        
        t1.start();
        t2.start();
    }

五、中断线程

  使用的方法:public void interrupt():中断线程。如果线程在调用Object类的wait()、wait(long)或wait(long ,int)方法,或者该类的join()、join(long)、join(long,int)、sleep(long)\sleep(long,int)方法中受阻,则其中断状态被清除,它还将收到一个InterruptException。

线程控制

标签:

原文地址:http://www.cnblogs.com/orlion/p/4833878.html

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