线程控制
一、线程休眠 使用的方法: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"; void run(){ try { // 休眠1s Thread.sleep(1000); } catch (InterruptedException e) { TODO Auto-generated catch block e.printStackTrace(); } System.out.print(res); } } 二、线程加入 使用的方法:public void join():等待该线程终止 当对线程对象调用此方法时,只有当该线程执行完毕后其他线程才可以执行。 static main(String[] args) { Test t = new Test(); Thread t1 = Thread(t); Thread t2 = Thread(t); { t1.join(); } e.printStackTrace(); } t1.start(); t1执行完t2才执行 t2.start(); } 三、线程礼让 使用的方法:public static void yield():暂停当前正在执行的线程,执行其他线程 class Runable1Demo Runnable{ run() { Thread.yield(); System.out.println(Thread.currentThread().getName()); } } 四、守护线程 使用的方法:public void setDaemon(boolean on):将该线程标记为守护线程或者是用户线程,on如果为true标记为守护线程。守护线程会在用户线程结束后被迫结束而不管有没有运行完,可以理解为守护线程守护服务于用户线程。
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。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |