停止线程


通常情况下用标记来停止线程

特殊情况:wait的线程,可以用interrupte让线程从冻结回到运行状态,但是这样会抛出InterruptedException

package com.xiaozhi.procon2;

public class Test2 {
	public static void main(String[] args) {
		MyRun myRun=new MyRun();
		Thread thread1=new Thread(myRun);
		Thread thread2=new Thread(myRun);
		thread1.start();
		thread2.start();
		try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}
		myRun.setFlag(false);
//		thread1.interrupt();
//		thread2.interrupt();
		System.out.println("--------------------------------------------------over");
	}
}

class MyRun implements Runnable{
	private boolean flag=true;
	@Override
	public synchronized void run() {
		while(flag){
//			try {this.wait();} catch (InterruptedException e) {System.out.println(Thread.currentThread().getName()+"---------------InterruptedException");}
			System.out.println(Thread.currentThread().getName()+"---------------run");
		}
	}
	public void setFlag(boolean flag) {
		this.flag = flag;
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值