package demo.thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class StopThread implements Runnable {
Lock lock = new ReentrantLock();
Condition con = lock.newCondition();
private boolean flag = true;
void setFlag() {
flag = false;
}
//标记法
/*
public void run() {
while (flag) {
System.out.println(Thread.currentThread().getName() + "...");
}
}*/
public synchronized void run() {
while (flag) {
try {
wait();//但是如果线程处于了冻结状态,无法读取标记。如何结束呢?
} catch (InterruptedException e) {
e.printStackTrace();
setFlag();
}
System.out.println(Thread.currentThread().getName() + "...");
}
}
}
class StopThreadTest {
public static void main(String[] args) {
StopThread t = new StopThread();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
t2.start();
int i = 0;
while (true) {
if (i++ == 50) {
// t.setFlag(); //标记法
t1.interrupt();//将线程从冻结状态强制恢复到运行状态中来,让线程具备cpu的执行资格,强制动作会发生异常,需要处理
t2.interrupt();
break;
}
System.out.println(Thread.currentThread().getName() + "...." + i);
}
}
}
线程停止方法
最新推荐文章于 2024-09-21 22:43:09 发布
该博客主要围绕线程停止方法展开,但具体内容缺失。推测会涉及线程停止的相关技术和操作,在信息技术领域,线程停止方法对于程序的稳定运行和资源管理至关重要。
5382

被折叠的 条评论
为什么被折叠?



