1.[代码][Java]代码
package boom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
//synchronized同步到单一对象
public class Test {
public static void main(String[] args) throws InterruptedException {
final Person per = new Person();
new Thread(){
public void run(){
per.f1();
}
}.start();
new Thread(){
public void run(){
per.f2();
}
}.start();
new Thread(){
public void run(){
per.f3();
}
}.start();
}
}
class Person {
private Lock lock = new ReentrantLock();
public void f1(){
lock.lock();
try{
for(int i = 0;i<2;i++){
System.out.print("f1\n");
}
}finally{
lock.unlock();
}
}
public void f2(){
lock.lock();
try{
for(int i = 0;i<2;i++){
System.out.print("f2\n");
}
}finally{
lock.unlock();
}
}
public void f3(){
lock.lock();
try{
for(int i = 0;i<2;i++){
System.out.print("f3\n");
}
}finally{
lock.unlock();
}
}
}