-
new Thread() {
-
public void run() {
-
output.output(“zhangsan”);
-
};
-
}.start();
-
new Thread() {
-
public void run() {
-
output.output(“lisi”);
-
};
-
}.start();
-
}
-
}
-
class Outputter1 {
-
private Lock lock = new ReentrantLock();// 锁对象
-
public void output(String name) {
-
// TODO 线程输出方法
-
lock.lock();// 得到锁
-
try {
-
for(int i = 0; i < name.length(); i++) {
-
System.out.print(name.charAt(i));
-
}
-
} finally {
-
lock.unlock();// 释放锁
-
}
-
}
-
}
这样就实现了和sychronized一样的同步效果,需要