public class StopThread implements Runnable { /* * 停止线程 * 1、stop 方法 * 2、run方法结束 * 怎么控制线程任务结束呢? * 任务中都会有循环结构,只要控制了循环就可以结束任务。 * 控制循环通常是通过定义标记来实现的 * 但如果线程处于冻结状态,无法读取标记,如何结束? * 可以使用interrupt()方法将线程从冻结状态强制恢复到运行状态中来,让线程具备cpu执行权 * 当强制动作发生了InterruptedException,记得要处理 * */ private boolean flag = true; @Override public synchronized void run() { while (flag){ try { wait(); } catch (InterruptedException e) { System.out.println(Thread.currentThread().getName()+"........"+e); flag = false; } System.out.println(Thread.currentThread().getName()+"........++++"); } } }
public class Test4 { public static void main(String[] args){ StopThread stopThread = new StopThread(); Thread thread = new Thread(stopThread); Thread thread1 = new Thread(stopThread); thread.start(); thread1.start(); int num = 1; for(;;){ if(++num==50){ thread.interrupt(); thread1.interrupt(); break; } System.out.println("main....."+num); } System.out.println("over"); } }