2013-07-04 18 views
0

所以不是「睡眠」一個線程,如Thread.sleep();,只允許進程在另一個線程上運行,並使新線程睡眠Thread.sleep();而不是原始Thread。這可能嗎?如何在不同的線程上運行程序的某些部分並將線程引用變量?

這裏是我的方法,我想在一個名爲processesThreadThread運行:

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(); 

任何想法?

+0

不太確定你要在這裏做什麼,但我建議閱讀有關ExecutorService(http://www.javacodegeeks.com/2013/01/java-thread-pool-example-using-executors -and-threadpoolexecutor.html?ModPagespeed = noscript)(http://stackoverflow.com/questions/2104676/java-executor-best-practices)和一些官方文檔(http://docs.oracle.com/javase/6 /docs/api/java/util/concurrent/ExecutorService.html),也許這可以幫助你,但你需要澄清你想要做什麼:) – AlejandroVK

+0

@AjjandroVK基本上,我不想要那個線程我的大部分程序都在運行,進入睡眠狀態。只是新的線程。 – knorberg

+0

先看看提供的鏈接,他們會在您的場景中爲您提供幫助,您需要擁有可由管理員控制的線程池。對於Executor來說這是一個完美的場景。否則,你可以自己實現,創建一個線程管理器,可以根據你指定的任何標準來休眠/啓動/停止每個線程。 – AlejandroVK

回答

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() - 這將喚醒所有線程。但是,只有其中一個線程能夠抓取顯示器(請記住等待處於同步塊中)並繼續運行 - 其他線程將被阻止,直到它們可以獲取顯示器的鎖定爲止。

+0

你介意我給你一個PasteBin鏈接來向你展示我的整個程序嗎?這會更容易!也許你可以告訴我如何實施你的方法? – knorberg

+0

我改變了這一點,並得到它的工作!謝謝! – knorberg

相關問題