欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java停止线程 博客分类: 多线程  

程序员文章站 2024-03-22 10:24:34
...

1、run方法正常结束

public class StopThreadDemo {
	public static void main(String[] args) {
		PrintThread pt = new PrintThread();
		pt.start();
	}
}

class PrintThread extends Thread {
	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println("print : " + i);
		}
	}
}

 

2、可以在run方法中设置标记让线程正常结束

public class StopThreadDemo {
	public static void main(String[] args) {
		PrintThread pt = new PrintThread();
		pt.start();
	}
}

class PrintThread extends Thread {
	int i = 0;
	boolean isStop = false;
	
	public void run() {
		while(!isStop) {
			if ((i++) == 10) {
				isStop = true;
			}
			
			System.out.println("print : " + i);
		}
	}
}

 

3、当线程处于冻结状态,没有指定的方式恢复到运行状态时,这时需要对冻结状态进行清除 强制让线程恢复到运行状态中来,这样就可以操作标记,让线程结束 Thread类中提供了该方法  interrupt()方法

public class StopThreadDemo {
	public static void main(String[] args) {
		StopThread st = new StopThread();

		Thread t1 = new Thread(st);
		Thread t2 = new Thread(st);

		t1.start();
		t2.start();

		int num = 0;
		while (true) {
			if (num++ == 60) {
				// st.changeFlag();
				/*
				 * interrupt方法只作用于那些因为执行了sleep、wait、join方法而休眠的线程,使他们不再休眠
				 */
				t1.interrupt();
				t2.interrupt();
				break;
			}

			System.out
					.println(Thread.currentThread().getName() + "....." + num);
		}

		System.out.println("over");
	}
}

class StopThread implements Runnable {
	private boolean flag = true;

	@Override
	public synchronized void run() {
		while (flag) {
			try {
				wait();
			} catch (InterruptedException e) { // 可以在异常代码块中处理让线程正常退出或强制线程退出(return)
				System.out.println(Thread.currentThread().getName()
						+ ".....Exception.....");
				flag = false;
			}

			System.out.println(Thread.currentThread().getName()
					+ ".....run.....");
		}
	}

	public void changeFlag() {
		flag = false;
	}
}