實現介面runnable
實現介面callable(結合執行緒池)
實現callable介面或者runnable介面
呼叫如下方法即可
結束任務
執行緒池方式:
`//初始化執行緒池
executorservice pool = executors.newfixedthreadpool(2);
//可以執行runnable物件或者callable物件代表的執行緒
futurefuture = pool.submit(new callable()
return sum;
}});
//獲取結果
try catch (interruptedexception e) catch (executionexception e)
//結束
pool.shutdown();`
使用futuretask轉化
futuretasktask = new futuretask(new callable()
return sum;
}});
thread t = new thread(task);
t.start();
try catch (interruptedexception e) catch (executionexception e)
}public class student catch (interruptedexception e)
}// 設定資料
this.name = name;
this.age = age;
// 修改標記
this.flag = true;
this.notify();
}public synchronized void get() catch (interruptedexception e)
}// 獲取資料
system.out.println(this.name + "---" + this.age);
// 修改標記
this.flag = false;
this.notify();}}
public class getthread implements runnable
public void run()
}}public class setthread implements runnable
public void run() else
x++;}}
}
Java基礎之多執行緒
1.多執行緒的實現方式 1.繼承thread public class demo2 thread class mythread extends thread 2.實現runnable介面public class demo3 runnable class myrunnable implements r...
Java之多執行緒
執行緒的狀態 繼承thread類和實現runable介面,新執行緒執行,即是執行run 方法裡的內容 public class testthread extends thread if count 10 0 catch interruptedexception e run方法結束即當前執行緒結束 p...
java之多執行緒
建立乙個執行緒的方法有三種,thread,runnable 實現,實現callable call 作為實體,可以返回try,catch 1.thread t new thread 2.class x implements runable thread t new thread new x 3.cal...