1. 程式人生 > >多個執行緒訪問synchronized和非synchronized程式碼塊

多個執行緒訪問synchronized和非synchronized程式碼塊

class Counter implements Runnable{ private int count;

public Counter() { count = 0; }

public void countAdd() { synchronized(this) { for (int i = 0; i < 5; i ++) { try { System.out.println(Thread.currentThread().getName() + “:” + (count++)); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }

//非synchronized程式碼塊,未對count進行讀寫操作,所以可以不用synchronized public void printCount() { for (int i = 0; i < 5; i ++) { try { System.out.println(Thread.currentThread().getName() + " count:" + count); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }

public void run() { String threadName = Thread.currentThread().getName(); if (threadName.equals(“A”)) { countAdd(); } else if (threadName.equals(“B”)) { printCount(); } } } 呼叫程式碼: Counter counter = new Counter(); Thread thread1 = new Thread(counter, “A”); Thread thread2 = new Thread(counter, “B”); thread1.start(); thread2.start(); 執行結果: A:0 B count:1 A:1 B count:2 A:2 B count:3 A:3 B count:4 A:4 B count:5