Java 語言提供兩個基本的同步機制:synchronized 方法(synchronized methods )和 synchronized 語句(synchronized statements)。
示例先大概說一下 Java Synchronized 關鍵字,當它用來修飾一個方法或者一個代碼塊的時候,能夠保證在同一時刻只有一個線程執行該段代碼。
如下代碼所示:
package cn.db.syncdemo;
public class NewClass {/**
* 同步方法
*/
public void synchronizedMethod() { synchronized (this) {int i = 5;
while (i-- > 0) {System.out.PRintln(Thread.currentThread().getName() + " : " + i
+ " synchronized method");
try {Thread.sleep(2000);
} catch (InterruptedException e) {System.out.println(e.toString());
}
}
}
}
/**
* 同步方法 2
*/
public void synchronizedMethod2() { synchronized (this) {int i = 5;
while (i-- > 0) {System.out.println(Thread.currentThread().getName() + " : " + i
+ " synchronized method 2");
try {Thread.sleep(1000);
} catch (InterruptedException e) {System.out.println(e.toString());
}
}
}
}
/**
* 非同步方法
*/
public void nonSynchronizedMethod() {int i = 5;
while (i-- > 0) {System.out.println(Thread.currentThread().getName() + " : " + i
+ " nonSynchronized method");
try {Thread.sleep(1000);
} catch (InterruptedException e) {System.out.println(e.toString());
}
}
}
public static void main(String[] args) {final NewClass mClass = new NewClass();
// t1 和 t2 都要訪問同一個同步方法 synchronizedMethod
Thread t1 = new Thread(new Runnable() { public void run() {mClass.synchronizedMethod();
}
}, "Thread 1");
Thread t2 = new Thread(new Runnable() { public void run() {mClass.synchronizedMethod();
}
}, "Thread 2");
// t3 要訪問另一個同步方法 synchronizedMethod2
Thread t3 = new Thread(new Runnable() { public void run() {mClass.synchronizedMethod2();
}
新聞熱點
疑難解答