Java多執行緒16:使用ReentrantLock類實現同步操作
阿新 • • 發佈:2018-12-14
在Java多執行緒中,可以使用synchronized關鍵字來實現執行緒之間同步互斥,但在JDK1.5中新增加了ReentrantLock類也能達到同步的效果,並且在擴充套件功能上也更加強大。
package unit3; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Demo6_Run { public static void main(String[] args) { MyService service = new MyService(); MyThread a1 = new MyThread(service); MyThread a2 = new MyThread(service); MyThread a3 = new MyThread(service); MyThread a4 = new MyThread(service); MyThread a5 = new MyThread(service); /*System.out.println(a1.getName()); System.out.println(a2.getName()); System.out.println(a3.getName()); System.out.println(a4.getName()); System.out.println(a5.getName());*/ a1.start(); a2.start(); a3.start(); a4.start(); a5.start(); } } class MyThread extends Thread { private MyService service; public MyThread(MyService service) { super(); this.service = service; } public void run() { service.testMethod(); } } class MyService { private Lock lock = new ReentrantLock(); public void testMethod() { lock.lock(); for (int i = 0; i < 5; i++) { System.out.println("ThreadName=" + Thread.currentThread().getName() + (" " + (i + 1))); } lock.unlock(); } }
從執行結果來看,當前執行緒列印完畢之後將鎖進行釋放,其他執行緒才可以繼續列印。執行緒列印的資料是分組列印,應為當前執行緒已經持有鎖,但執行緒之間列印順序是隨機的。