线程中更改全局变量的问题

来源:互联网 发布:php好就业吗 编辑:程序博客网 时间:2024/05/23 14:18
线程中更改全局变量例子:
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())才能更改,或许会是因为线程尚未开始就已经进行了输出结果。