close
使用多線程來跑程式的時候,有時候會遇到資源共享的問題造成記憶體或其他資料的非同步或是不對稱。
當遇到這類型的問題時,就會想確保線程中某個使用共同變數的程式先執行完,再繼續其他線程的運作。
下述的程式碼就是執行兩個線程(一般的多線程):
package Test; public class ThreadAndSynchronized implements Runnable{ private int num = 0; public ThreadAndSynchronized(int i){ this.num = i; } @Override public void run() { // TODO Auto-generated method stub for(int i=0;i<5;i++) System.out.println("Thread: " + num); } public static void main(String args[]){ ThreadAndSynchronized tas1 = new ThreadAndSynchronized(1); Thread t1 = new Thread(tas1,"Thread 1"); ThreadAndSynchronized tas2 = new ThreadAndSynchronized(2); Thread t2 = new Thread(tas2,"Thread 2"); t1.start(); t2.start(); } }
執行結果:
Thread: 2 Thread: 1 Thread: 2 Thread: 1 Thread: 1 Thread: 2 Thread: 1 Thread: 1 Thread: 2 Thread: 2 |
但是如果 run() 函數中的某個值是希望被執行完畢再進行下一步,我們就可以用 synchronized(Name.class){} 來強迫執行完才可以繼續其他行為。
程式碼如下:
package Test; public class ThreadAndSynchronized implements Runnable{ private int num = 0; public ThreadAndSynchronized(int i){ this.num = i; } @Override public void run() { // TODO Auto-generated method stub synchronized(ThreadAndSynchronized.class){ for(int i=0;i<5;i++) System.out.println("Thread: " + num); } } public static void main(String args[]){ ThreadAndSynchronized tas1 = new ThreadAndSynchronized(1); Thread t1 = new Thread(tas1,"Thread 1"); ThreadAndSynchronized tas2 = new ThreadAndSynchronized(2); Thread t2 = new Thread(tas2,"Thread 2"); t1.start(); t2.start(); } }
執行結果
Thread: 1 Thread: 1 Thread: 1 Thread: 1 Thread: 1 Thread: 2 Thread: 2 Thread: 2 Thread: 2 Thread: 2 |
全站熱搜
留言列表