java多线程lock的使用
看代码:
package com.ming.thread.reentrantlock; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class MyService { private Lock lock=new ReentrantLock(); public void testMethodA(){ lock.lock(); for(int i=0;i<5;i++){ System.out.println("方法A"+"ThreadName="+Thread.currentThread().getName()+"("+(i+1)+")"); } lock.unlock(); } public void testMethodB(){ lock.lock(); for(int i=0;i<5;i++){ System.out.println("方法B"+"ThreadName="+Thread.currentThread().getName()+"("+(i+1)+")"); } lock.unlock(); } }
package com.ming.thread.reentrantlock; public class ThreadA extends Thread{ private MyService service; public ThreadA(MyService service){ super("A"); this.service=service; } public void run(){ service.testMethodA(); } }
package com.ming.thread.reentrantlock; public class ThreadB extends Thread{ private MyService service; public ThreadB(MyService service){ super("B"); this.service=service; } public void run(){ service.testMethodB(); } }
package com.ming.thread.reentrantlock; public class Run { public static void main(String[] args) { MyService service=new MyService(); ThreadA a=new ThreadA(service); ThreadB b=new ThreadB(service); a.start(); b.start(); } }
更多运用:http://blog.csdn.net/vking_wang/article/details/9952063