java中synchronized塊是怎么用的給個例子
以下兩個例子說明synchronized塊的用法:
馬克- to-win:馬克 java社區(qū):防盜版實名手機尾號: 73203。
例1.9.4_a-本章源碼
class A {
public void disp() {
System.out.println("新線程馬克-to-win啟動:");
for (int i = 0; i < 10; i++) {
System.out.println(i);
try {
Thread.sleep(500);
} catch (Exception e) {
}
}
}
}
public class TestMark_to_win extends Thread {
A a;
public TestMark_to_win(A a) {
this.a = a;
}
public void run() {
a.disp();
}
public static void main(String[] args) {
A a = new A();
TestMark_to_win t1 = new TestMark_to_win(a);
TestMark_to_win t2 = new TestMark_to_win(a);
t1.start();
t2.start();
}
}
運行結(jié)果是:
新線程啟動:
新線程啟動:
0
0
1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9
例1.9.4_b-本章源碼
class A {
public void disp() {
synchronized (this) {
System.out.println("新線程馬克-to-win啟動:");
for (int i = 0; i < 10; i++) {
System.out.println(i);
try {
Thread.sleep(500);
} catch (Exception e) {
}
}
}
}
}
public class TestMark_to_win extends Thread {
A a;
public TestMark_to_win(A a) {
this.a = a;
}
public void run() {
a.disp();
}
public static void main(String[] args) {
A a = new A();
TestMark_to_win t1 = new TestMark_to_win(a);
TestMark_to_win t2 = new TestMark_to_win(a);
t1.start();
t2.start();
}
}
運行結(jié)果是
新線程啟動:
0
1
2
3
4
5
6
7
8
9
新線程啟動:
0
1
2
3
4
5
6
7
8
9
之后本節(jié)有關(guān)synchronized的內(nèi)容(特別是有關(guān)ReentrantLock的部分),初學者可以略過。直接跳到學死鎖。