Lock比传统线程模型中的synchronized方式更加面向对象,与生活中的锁类似,锁本身也是应该是一个对象。两个线程执行的代码片段要实现同步互斥的效果,他们必须使用的是用一个Lock对象。锁是上在代表要操作的资源的类的内部方法中,而不是线程代码中。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
*Lock
*/
public class ThreadTest2 {
public static void main(String[] args) {
Outer out=new Outer();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.syso("#####");
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.syso("!!!!");
}
}
}).start();
}
static class Outer{
Lock lock=new ReentrantLock();
public void syso(String name){
lock.lock();
try{
for(int i=0,n=name.length();i<n;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}finally{
lock.unlock();
}
}
}
}