[英]Java Get multiple threads of different classes to run concurrently
我不確定問題到底是什么,但是由於某種原因,我無法從兩個類中同時運行線程。 我可以從一個類中同時運行多個線程,但是當我嘗試啟動另一個類時,什么也沒有發生。
public professor(){
prof = new Thread();
prof.start();
System.out.println("Prof has started1");
}
public void run(){
try{
System.out.println("Prof has started2");
prof.sleep(600);
//do more stuff
}
catch(Exception e){
System.out.println("Prof error");
}
這就是我開始第二堂課的方式,第一堂課以完全相同的方式開始並且運行良好。 但是,在該類中顯示“教授已開始1”,但第二個從不顯示。 我想念什么嗎?
我認為這是原因
prof = new Thread();
prof.start();
此代碼永遠不會調用您自己的run()
方法,如果您的類實現了runnable接口,則應執行此操作
prof = new Thread(this)
prof.start()`
您沒有提供完整的Professor類,所以確切的解決方案可能有所不同,但是我要注意的重點是:創建Thread
類的實例,然后調用.start()
:
prof = new Thread();
prof.start()
,當您在其上調用.start()
時, Thread
類本身不會執行任何操作。 您需要告訴它,一旦它被start()
ed后,您希望它執行什么動作。 有幾種方法可以做到這一點,但我會這樣做:
public professor() {
prof = new Thread(new Runnable() {
public void run() {
try {
System.out.println("Prof has started2");
Thread.currentThread().sleep(600);
//do more stuff
}
catch(Exception e){
System.out.println("Prof error");
}
}
});
prof.start();
System.out.println("Prof has started1");
}
public void run() {
}
那就是:創建一個Runnable
實例,在其中您重寫run()
使其可以執行您想要的任何操作。 然后將此Runnable
實例傳遞給您正在創建的Thread
對象的構造函數。 當您隨后調用.start()
將run()
該Runnable
的run()
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.