一. 简要说明:
除了对方法进行Synchronized以便实现线程的同步之外,还可以对对象进行Synchronized的修饰,这种方式称为Synchronized程序段。此时,同一个对象的程序段一次只允许一个线程使用它。
二. 例子:
public class ThreadSyncObjTest implements Runnable {
private String str = new String();
private Integer delay = new Integer(1);
public static void main(String args[]) {
ThreadSyncObjTest r = new ThreadSyncObjTest();
Thread t;
for (int i=0; i<=2; i++) {
t = new Thread(r);
t.start();
}
System.out.println("end main");
}
public void run(){
for (int i = 0; i<=2; i++) {
//synchronized(System.out) {
//synchronized(str) {
synchronized(delay) { // 不能用基本类型
System.out.println(Thread.currentThread().getName());
System.out.println("count: "+ i);
}
}
}
}
三. 测试结果:
/*
Thread-0
count: 0
Thread-0
count: 1
Thread-0
count: 2
Thread-2
count: 0
Thread-2
count: 1
Thread-2
count: 2
end main
Thread-1
count: 0
Thread-1
count: 1
Thread-1
count: 2
*/
四. 说明:
1. 注意 end main的打印位置,由于这个线程是用户线程,所以,即使主程序结束,这个线程也可能没有结束。这在前前篇已经有详细的说明与举例。
2. 每个线程的两个打印语句总是两两显示在一起,没有出现混乱的现象。
3. synchronized后面括号中的不能是基本数据类型,必须是对象,当然,也可以是this。