public class SynchronizedCounter {private int c = 0;
public synchronized void increment() {c++;}
public synchronized void decrement() {c--;}
public synchronized int value() {return c;}}
class MyRunnable implements Runnable {int var = 10;@Overridepublic void run() {call();}
public void call() {synchronized (this) {for (int i = 0; i < 4; i++) {var++;System.out.println("Current Thread " + Thread.currentThread().getName() + " var value "+var);}}}}
public class MutlipleThreadsRunnable {public static void main(String[] args) {MyRunnable runnable1 = new MyRunnable();MyRunnable runnable2 = new MyRunnable();Thread t1 = new Thread(runnable1);t1.setName("Thread -1");Thread t2 = new Thread(runnable2);t2.setName("Thread -2");Thread t3 = new Thread(runnable1);t3.setName("Thread -3");t1.start();t2.start();t3.start();}}
Without Synchronized keyword
Current Thread Thread -1 var value 11Current Thread Thread -2 var value 11Current Thread Thread -2 var value 12Current Thread Thread -2 var value 13Current Thread Thread -2 var value 14Current Thread Thread -1 var value 12Current Thread Thread -3 var value 13Current Thread Thread -3 var value 15Current Thread Thread -1 var value 14Current Thread Thread -1 var value 17Current Thread Thread -3 var value 16Current Thread Thread -3 var value 18
Current Thread Thread -1 var value 11Current Thread Thread -2 var value 11Current Thread Thread -1 var value 12Current Thread Thread -2 var value 12Current Thread Thread -1 var value 13Current Thread Thread -2 var value 13Current Thread Thread -1 var value 14Current Thread Thread -2 var value 14Current Thread Thread -3 var value 15Current Thread Thread -3 var value 16Current Thread Thread -3 var value 17Current Thread Thread -3 var value 18
class A {public static synchronized void methodA() {// all function code}
equivalent to
public void methodA() {synchronized(A.class) {// all function code}}}
同步语句(使用变量)
class A {private Object lock1 = new Object();
public void methodA() {synchronized(lock1 ) {// all function code}}}
// rest of the code
class Buffer {private int counter = 0;// added synchronized keyword to let only one thread// be it inc or dec thread to manipulate data at a timepublic synchronized void inc() { counter++; }public synchronized void dec() { counter--; }public int getCounter() { return counter; }}
// rest of the code