我有一個通過實作 Runnable 介面創建的執行緒。我的任務是:執行緒應該計數(從 0 開始)并將它達到的值保存到一個變數中,該變數是主類的一部分。我覆寫了 run 方法并進行了計數,但是如何將此值保存到 main 的變數中?只有吸氣劑是解決方案嗎?我的執行緒類:
public class myThread implements Runnable {
private static int count = 0;
private final int length;
public myThread (int length) {
this.length = length;
}
@Override
public void run() {
while (count < this.length) {
increaseValue();
}
}
private void increaseValue() {
synchronized (ThreadFirstExercise.class) {
if (count < this.length) {
this.count ;
}
}
}
}
主要的:
public class Main {
public static void main(String[] args) {
int result; // this is the variable where I want to save the counting result of my thread
(new Thread(new ThreadFirstExercise(10000))).start();
}
}
uj5u.com熱心網友回復:
您可以使用Callable回傳 a 的 a Future。或者,您可以在包含整數的 main 方法中使用包裝物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/486652.html
