在java1.5中Lock对象来实现同步的效果,而且使用上更方便。

public class MyService {

    private Lock lock = new ReentrantLock();
    
    public void methodA(){
        try {
            lock.lock();
            System.out.println("methodA begin threadName=" + Thread.currentThread().getName()+" time="+System.currentTimeMillis());
            Thread.sleep(5000);
            System.out.println("methodA end threadName=" + Thread.currentThread().getName()+" time="+System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    
    public void methodB(){
        try {
            lock.lock();
            System.out.println("methodB begin threadName=" + Thread.currentThread().getName()+" time="+System.currentTimeMillis());
            Thread.sleep(5000);
            System.out.println("methodB end threadName=" + Thread.currentThread().getName()+" time="+System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

public class Test {
    public static void main(String[] args) throws InterruptedException {
        MyService service = new MyService();
        new Thread(()->service.methodA()).start();
        new Thread(()->service.methodA()).start();
        new Thread(()->service.methodB()).start();
        new Thread(()->service.methodB()).start();

    }
}
View Code

相关文章: