java中synchronized块是怎么用的给个例子
以下两个例子说明synchronized块的用法:
马克- to-win:马克 java社区:防盗版实名手机尾号: 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();
}
}
运行结果是:
新线程启动:
新线程启动:
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();
}
}
运行结果是
新线程启动:
0
1
2
3
4
5
6
7
8
9
新线程启动:
0
1
2
3
4
5
6
7
8
9
之后本节有关synchronized的内容(特别是有关ReentrantLock的部分),初学者可以略过。直接跳到学死锁。