[code="java"]
package com.zzf.thread;
public class Test_03 {
public static void main(String[] args) {
// TODO 自动生成方法存根
TxtThread tt = new TxtThread();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
}
}
class TxtThread implements Runnable {
int num = 20;
String str = new String();
public void run() {
while (true) {
synchronized (str) {//这里的锁?
if (num > 0) {
try {
Thread.sleep(10);
} catch (Exception e) {
e.getMessage();
}
System.out.println(Thread.currentThread().getName()
+ "this is " + num--);
}
}
}
}
}
[/code]
输出结果:
Thread-0this is 20
Thread-0this is 19
Thread-0this is 18
Thread-0this is 17
Thread-0this is 16
Thread-0this is 15
Thread-0this is 14
Thread-0this is 13
Thread-0this is 12
Thread-0this is 11
Thread-0this is 10
Thread-0this is 9
Thread-3this is 8
Thread-3this is 7
Thread-3this is 6
Thread-3this is 5
Thread-3this is 4
Thread-3this is 3
Thread-3this is 2
Thread-3this is 1
我不明白的是:TxtThread也是一个类,每创建一个它的对象就会拥有它的属性,因此num,str不是共享的,不存在访问冲突的情况
另外代码中synchronized (str) //这里获取的锁是哪一个对象的?我不是太懂synchronized的使用方法和原理