public class StopThread implements Runnable {
private boolean flag=true;
@Override
public void run() {
while(flag){
System.out.println(Thread.currentThread().getName()+"....");
}
}
public void setFlag(){
flag=false;
}
}
//main
StopThread st = new StopThread();
Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
t1.start();
t2.start();
Thread.sleep(1000);
st.setFlag();
t1.interrunpt()
setDaemon 前台线程必须手动结束,如果所有前台线程都结束了,后台线程都必须跟着结束
StopThread st = new StopThread();
Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
t1.start();
t2.setDaemon();
t2.start();
Thread.sleep(1000);
t1.setFlag(); //t1结束后,t2跟着结束
t1.join()
,等待t1中断或完成,常用于中间加入进来必须执行的线程 t1.start(); t1.join(); t2.start();
PRIORITY
Thread.currentThread() //可以显示优先级
t1.start();
t2.start();
t2.setPriority(Thread.MAX_PRIORITY);
Thread.sleep(1000);
st.setFlag();
//Thread[Thread-1,10,main]....
暂停,释放执行权