1、线程停止
推荐线程自己停下来
一般是以标志位的方式终止线程,flag=false
public class StopThread implements Runnable{
//标志位
private flag = true;
@Override
public void run(){
//线程题使用标志位
while(flag){
System.out.println("run Tread");
}
}
//对外提供方法使用
public void stop(){
this.flag=false;
}
}
这样在进程中调用:
public void main (String[] arg){
StopThread stopInstance = new StopThread ();
new Tread(stopInstance).start();
for(int i = 0;i<1000;i++){
System.out.println("run Tread"+i);
if(i==900){
stopInstance.stop()
}
}
这样,进程在900的时候就可以停止。
2、线程休眠
Tread.sleep(1000);
3、线程礼让
Tread.yield(1000);
4、线程强制执行
join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞
public class JoinThread implements Runnable {
@Override
public void run() {
//线程题使用标志位
for (int i = 0; i < 1000; i++) {
System.out.println("run Tread" + i);
}
}
public static void main(String[] arg) throws InterruptedException {
JoinThread joinInstance = new JoinThread();
Thread thread = new Thread(joinInstance);
thread.start();
//主线程
for (int i = 0; i < 1000; i++) {
System.out.println("main" + i);
if (i == 900) {
thread.join();//join线程插队
}
}
}
}