我正在尝试使用带有中断方法的两个线程来打印偶数。
我从互联网上查阅了代码,并编写了如下所示的代码。它可以正确打印,但是在打印20后程序正在继续执行。
oldNum
,则检查代码可以正常工作。有没有提供oldNum
检查的逻辑? Thread.sleep(1000L)
,则它仅打印“偶数线程打印20”并继续执行。这是怎么回事? run()
方法内部和main方法的for循环内部提供了断点,run()
方法的断点没有命中。为什么会这样? 简而言之,我想知道这里的代码流是什么。
谢谢
维卡什
public class PrintOddEvenUsingInterrupt {
public static volatile int count;
public static void main(String[] args) throws InterruptedException {
Thread oddThread = new Thread(new OddInterruptThread(), "Odd Thread ");
Thread evenThread = new Thread(new EvenInterruptThread(),"Even Thread ");
oddThread.start();
evenThread.start();
for (int i = 0; i < 20; i++) {
count++;
oddThread.interrupt();//Break points works here
evenThread.interrupt();
Thread.sleep(1000L);// Line-a
}
}
static class OddInterruptThread implements Runnable {
public void run() {
int oldNum = 0;//Break points doesn't works here
while (true) {
try {
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
}
if (oldNum != count && count % 2 == 1) {
System.out.println(Thread.currentThread().getName()
+ " prints " + count);
oldNum = count;
}
}
}
}
static class EvenInterruptThread implements Runnable {
public void run() {
int oldNum = 0;//Break points doesn't works here
while (true) {
try {
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
}
if (oldNum != count && count % 2 == 0) {
System.out.println(Thread.currentThread().getName()
+ " prints " + count);
oldNum = count;
}
}
}
}
}
最佳答案
您的程序没有停止的原因是:当您的主线程退出时,您的奇数和偶数线程会陷入无限循环。
您将需要定义一个停止条件,线程才能出来。
实现此目的的一种方法是通过使用条件。
例如:
public volatile static boolean oddFinished = false;
public volatile static boolean evenFinished = false;
然后在您的线程中,而不是无限循环,而是针对条件循环
而(!oddFinished){
//还可以将线程 sleep 状态更改为 sleep 较少的时间间隔(例如1000L或程序要等待的任何时间)
}
对偶数线程也做同样的事情...
while (! evenFinished){
// also change your thread sleep to sleep for fewer time interval (say 1000L or whatever your program wants to wait for)
}
在主线程中,可以在for循环结束后添加以下代码...
oddFinished = true;
evenFinished = true;
oddThread.join();
evenThread.join();
这将使您的代码正常停止。
关于java - 使用中断方法打印偶数时会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54499939/