Java語法規定,任何線程進入同步方法、同步代碼塊之前,必須先獲取同步方法、同步代碼塊對應的同步監視器。
對於同步代碼塊而言,程序必須爲它顯示的指定同步監視器(可爲this也可以自定義Object類型的全局變量);對於同步非靜態方法而言,該方法的同步
監視器是this----即調用該方法的java對象;對於靜態的同步方法而言,該方法的同步監視器不是this而是該類本身。
public class SynchronizedStatic implements Runnable {
static boolean staticFlag = true;
public static synchronized void test0(){
for(int i=0;i<5;i++){
System.out.println("test0:"+Thread.currentThread().getName() + " "+ i);
}
}
public void test1(){
synchronized (this) {
// synchronized (SynchronizedStatic.class) {
for(int i=0;i<5;i++){
System.out.println("test1:"+Thread.currentThread().getName() + " "+ i);
}
}
}
public void run() {
if(staticFlag){
staticFlag = false;
test0();
}else{
staticFlag = true;
test1();
}
}
public static void main(String[] args) throws InterruptedException {
SynchronizedStatic ss = new SynchronizedStatic();
new Thread(ss).start();
//保證第一條線程開始運行
// Thread.sleep(1);
new Thread(ss).start();
}
}
執運行效果如下:
test0:Thread-0 0
test0:Thread-0 1
test1:Thread-1 0
test1:Thread-1 1
test1:Thread-1 2
test1:Thread-1 3
test1:Thread-1 4
test0:Thread-0 2
test0:Thread-0 3
test0:Thread-0 4
顯然是併發執行,並沒有達到同步執行(順序執行)的效果。
public void test1(){
// synchronized (this) {
synchronized (SynchronizedStatic.class) {
for(int i=0;i<5;i++){
System.out.println("test1:"+Thread.currentThread().getName() + " "+ i);
}
}
}
執行結果如下:
test0:Thread-0 0
test0:Thread-0 1
test0:Thread-0 2
test0:Thread-0 3
test0:Thread-0 4
test1:Thread-1 0
test1:Thread-1 1
test1:Thread-1 2
test1:Thread-1 3
test1:Thread-1 4
,從而達到了線程同步的效果。
類似於Java併發編程:synchronized 中的
三.synchronized同步方法或者同步塊類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
public class Test
{ public static void main(String[]
args) { final InsertData
insertData = new InsertData(); new Thread(){ @Override public void run()
{ insertData.insert(); } }.start(); new Thread(){ @Override public void run()
{ insertData.insert1(); } }.start(); } } class InsertData
{ public synchronized void insert(){ System.out.println( "執行insert" ); try { Thread.sleep( 5000 ); } catch (InterruptedException
e) { e.printStackTrace(); } System.out.println( "執行insert完畢" ); } public synchronized static void insert1()
{ System.out.println( "執行insert1" ); System.out.println( "執行insert1完畢" ); } } |