private Lock lock = new ReentrantLock(); publicvoidtestMethod(){ lock.lock(); for (int i = 0 ;i < 5;i++){ System.out.println("ThreadName = " + Thread.currentThread().getName() + (" " + (i + 1))); } lock.unlock(); } }
测试的代码如下:
1 2 3 4 5 6 7 8
MyConditionService service = new MyConditionService(); new Thread(service::testMethod).start(); new Thread(service::testMethod).start(); new Thread(service::testMethod).start(); new Thread(service::testMethod).start(); new Thread(service::testMethod).start();
publicvoidtestMethod()throws Exception { MyConditionMoreService service = new MyConditionMoreService(); ThreadA a = new ThreadA(service); a.setName("A"); a.start();
ThreadA aa = new ThreadA(service); aa.setName("AA"); aa.start();
ThreadB b = new ThreadB(service); b.setName("B"); b.start();
ThreadB bb = new ThreadB(service); bb.setName("BB"); bb.start();
methodA begin ThreadName=A time=1485590913520 methodA end ThreadName=A time=1485590918522 methodA begin ThreadName=AA time=1485590918522 methodA end ThreadName=AA time=1485590923525 methodB begin ThreadName=B time=1485590923525 methodB end ThreadName=B time=1485590928528 methodB begin ThreadName=BB time=1485590928529 methodB end ThreadName=BB time=1485590933533