摘要: 有了synchronized關(guān)鍵字,多線程程序的運行結(jié)果將變得可以控制。synchronized關(guān)鍵字用于保護共享數(shù)據(jù)。請大家注意"共享數(shù)據(jù)",你一定要分清哪些數(shù)據(jù)是共享數(shù)據(jù),JAVA是面向?qū)ο蟮某绦蛟O(shè)計語言,所以初學(xué)者在編寫多線程程序時,容易分不清哪些數(shù)據(jù)是共享數(shù)據(jù)。請看下面的例子:
實例一:
public class FirstThread implements Runnable{
public synchronized void run(){
for(int i=1;i<10;i++){
System.out.println(""+i);
}
}
public FirstThread(){
}
public static void main(String[] args){
Runnable r1=new FirstThread();
Runnable r2=new FirstThread();
Thread t1=new Thread(r1);
Thread
閱讀全文