執行緒中更改全域性變數的問題
阿新 • • 發佈:2019-02-07
執行緒中更改全域性變數例子:
package 併發程式設計;
public class ConcurrencyTest {
public static volatile long count = 100001;
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
concurrency();
Thread.sleep(2000);
System.out.println(count);
}
private static synchronized void concurrency(){
Thread thread=new Thread(new Runnable(){
@Override
public synchronized void run() {
// TODO Auto-generated method stub
count=50;
//System.out.println(count);
}
});
thread.start();
//count=50;
//System.out.println(count);
}
}
注意@@@
package 併發程式設計;
public class ConcurrencyTest {
public static volatile long count = 100001;
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
concurrency();
Thread.sleep(2000);
System.out.println(count);
}
private static synchronized void concurrency(){
Thread thread=new Thread(new Runnable(){
@Override
public synchronized void run() {
// TODO Auto-generated method stub
count=50;
//System.out.println(count);
}
});
thread.start();
//count=50;
//System.out.println(count);
}
}
注意@@@
//線上程中更改全域性變數,只有在執行緒結束後(Thread.sleep())才能更改,或許會是因為執行緒尚未開始就已經進行了輸出結果。
上方為錯誤:實際應為主執行緒等所有子執行緒完成後再執行,才能達到更改值的效果