【发布时间】:2015-10-29 15:12:38
【问题描述】:
我正在尝试提供一种解决方案,让线程可以暂停并准确地从中断的地方恢复。
所以这是一个模拟我的问题的示例代码:2 个线程在后台运行:taskThread 和busyThread。当busyThread 处于系统繁忙区域 时,taskThread 必须立即 alt/暂停并准确地从中断处恢复。例如,如果taskThread 在任务 C(已完成)处暂停,它应该在 D 处继续。
我尝试使用等待,在 taskThread 上通知但没有成功。
public class Test
{
private Thread taskThread;
private Thread busyThread;
public static void main(String args[]) throws Exception
{
Test t = new Test();
t.runTaskThread();
t.runBusyThread();
}
public void runTaskThread()
{
taskThread = new Thread(new Runnable(){
@Override
public void run()
{
for (int x=0; x<100; x++)
{
try
{
System.out.println("I'm doing task A for process #"+x);
Thread.sleep(1000);
System.out.println("I'm doing task B for process #"+x);
Thread.sleep(200);
System.out.println("I'm doing task C for process #"+x);
Thread.sleep(300);
System.out.println("I'm doing task D for process #"+x);
Thread.sleep(800);
System.out.println("\n\n");
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}});
taskThread.start();
}
public void runBusyThread()
{
busyThread = new Thread(new Runnable(){
@Override
public void run()
{
while (true)
{
Random rand = new Random();
int randomNum = rand.nextInt(1000);
if (randomNum<400)
{
System.out.println("Wait...system is busy!!!");
try
{ //what should come here to to signal taskThread to paused
Thread.sleep(3000);
//what should come here to to signal taskThread to resume
} catch (InterruptedException e)
{
}
} else
{
try
{
Thread.sleep(300);
} catch (InterruptedException e)
{
}
}
}
}});
busyThread.start();
}
}
【问题讨论】:
-
只是一个简单的问题,你想停止一个线程然后从它的左右开始吗?
-
好点。不,我希望 alt/暂停(让我更改标题)谢谢!
-
如果你在线程需要停止时杀死线程并在需要恢复时创建一个新线程会发生什么,这会是一个问题吗?
-
是的,它必须从中断的地方继续;在现实世界的问题中,它转化为浪费时间
-
忙线程准备忙,但任务线程正在执行任务时会发生什么?
标签: java multithreading concurrency wait notify