因此,不要像 Thread.sleep();
那样“hibernate ”线程仅允许进程在另一个线程上运行并使新线程 sleep Thread.sleep();
但不是原来的Thread
。这可能吗?
这是我想要在新的 Thread
上运行的方法叫processesThread
:
private void Processes() throws IOException, InterruptedException {
// New Thread "processesThread" will start here.
Runtime rt = Runtime.getRuntime();
List<Process> processes = new ArrayList<Process>();
// "runnableTogether" will be the number that the user inputs in the GUI.
switch (runnableTogether) {
case 4:
processes.add(rt.exec("C:/Windows/System32/SoundRecorder.exe"));
case 3:
processes.add(rt.exec("C:/Windows/System32/taskmgr.exe"));
case 2:
processes.add(rt.exec("C:/Windows/System32/notepad.exe"));
case 1:
processes.add(rt.exec("C:/Windows/System32/calc.exe"));
Thread.sleep(5000);
destroyProcesses(processes);
break;
default:
System.exit(0);
break;
}
// New Thread "processesThread" will end here.
}
这可能吗?如果是这样,怎么办?
我研究过开始新的Threads
,但我不太清楚如何让它与我的程序一起工作。
编辑:我希望使用与此方法类似的方法:
Thread processesThread = new Thread() {
public void run() {
// Code here.
}
};
processesThread.start();
有什么想法吗?
最佳答案
如果我的问题正确,您想知道如何在当前线程保持运行状态时 hibernate 其他线程。您可以使用wait
和notify
.
这是一个例子;
final Object mon = ...;
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (mon) {
try {
mon.wait(); //blocks the t1 thread
} catch (InterruptedException e) {
//
}
}
}
});
mon.wait()
阻塞 t1 线程,直到另一个线程调用 mon.notify()
唤醒正在等待 mon
的线程目的。您也可以调用mon.notifyAll()
如果多个线程正在监视器上等待 - 这将唤醒所有线程。然而,只有一个线程能够获取监视器(请记住,等待是在同步块(synchronized block)中)并继续进行 - 其他线程将被阻塞,直到它们可以获得监视器的锁。
关于java - 如何在不同的线程上运行程序的某些部分并将变量引用到线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17463459/