我遇到了一個我的程序問題。總和數據在多個線程之間共享。它應該在每個線程添加到之後給出總和。線程之間的共享數據不對
public class ThreadPractise implements Runnable
{
Integer num;
String name;
volatile Integer commonSum;
Object lock;
public ThreadPractise(Integer i,String threadName ,Integer sum, Object sharedLock) {
num = i;
name = threadName;
commonSum =sum;
lock = sharedLock;
}
@Override
public void run() {
Integer cube = calculate(num);
update(cube);
System.out.println(Thread.currentThread().getName()+" has commonSum after update as "+commonSum);
}
public void update(Integer cube) {
synchronized (lock) {
this.commonSum = this.commonSum + cube;
System.out.println(Thread.currentThread().getName()+" has commonSum as "+commonSum);
}
}
public int calculate(Integer num2) {
return (num2*num2*num2);
}
public static void main(String[] args) {
Integer sum = new Integer(0);
Object lock = new Object();
for(int i=1;i<=3;i++)
{
Thread t = new Thread(new ThreadPractise(i, "Thread"+i, sum,lock));
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Sum of 1^3+2^3+3^3 = "+sum);
}
}
然而總和始終爲0。當我改變到的AtomicInteger其工作,但我需要的問題,這個實現。也請告訴我,我正在做的線程鎖定是否正確。
非常感謝。只是爲了增加這個問題。我對線程相對來說比較陌生。是我在程序中正在執行的鎖定權限。 – HariJustForFun
也只是一個懷疑的答案。我只在main中使用new關鍵字一次。然後,執行線程的變量版本是什麼。 – HariJustForFun
通常,您應該只鎖定「final」字段以確保始終鎖定在同一個實例上。除此之外,你的代碼看起來是正確的。然而,使用'AtomicInteger'將是更好的方法來處理併發,因爲它是* lock free *,因此運行更高性能。 –