在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

相关文章:

  • 2021-07-12
  • 2021-08-24
  • 2021-11-07
  • 2022-12-23
  • 2021-09-17
  • 2021-10-05
  • 2021-08-04
猜你喜欢
  • 2021-05-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-03
  • 2021-06-10
相关资源
相似解决方案