Lock比传统线程模型中的synchronized方式更加面向对象,与生活中的锁类似,锁本身也应该是一个对象。两个线程执行的代码片段要实现同步互斥的效果,它们必须使用同一个Lock对象。锁是上在代表要操作资源的类的内部方法中,而不是线程的代码中!
示例代码:
public class LockStudy {
public static void main(String[] args) {
final Output o = new Output();
//启动两个线程
new Thread(new Runnable() {
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
o.printName("wangjinglong");
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
o.printName("123456");
}
}
}).start();
}
}
class Output{
private Lock lock = new ReentrantLock();
public void printName(String name){
lock.lock();
for(int i = 0;i < name.length();i++){
System.out.print(name.charAt(i));
}
System.out.println();
lock.unlock();
}
}