0

So instead of "sleeping" a thread, as in Thread.sleep(); to merely allow the processes to run on another thread and make the new thread sleep with Thread.sleep(); but not the original Thread. Is this possible?

Here is my method that I want to run on a new Thread called 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.

    }

Is this possible? And if so, how?

I have researched starting new Threads, but I can't quite figure out how to get it to work with my program.

EDIT: I was hoping to use something similar to this approach:

Thread processesThread = new Thread() {
    public void run() {
        // Code here.
    }
};
processesThread.start();

Any ideas?

4

1 回答 1

1

如果我的问题是正确的,那么您想知道如何在当前线程保持运行状态时让其他线程休眠。您可以使用waitnotify

这是一个例子;

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()如果有多个线程在监视器上等待,您也可以调用- 这将唤醒所有线程。但是,只有一个线程能够获取监视器(请记住,等待是在同步块中)并继续进行 - 然后其他线程将被阻塞,直到它们可以获得监视器的锁。

于 2013-07-04T07:25:20.650 回答