读书人

使用synchronized跟Lock对象获取对象锁

发布时间: 2013-10-01 12:15:56 作者: rapoo

使用synchronized和Lock对象获取对象锁
package com.tch.test.concurrent;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class SynchronizedTest {private ExecutorService pool = Executors.newFixedThreadPool(4);private Lock lock = new ReentrantLock();public static void main(String[] args) {new SynchronizedTest().test();}public void test() {Runnable runnable = null;for(int i=0;i<4;i++){runnable = new Runnable(){public void run(){while(true){execute();}}};pool.execute(runnable);}}void execute(){lock.lock();//首先获得锁try{System.out.println(Thread.currentThread().getId()+"获得了lock,开始休息");Thread.sleep(300);}catch(Exception e){}finally{System.out.println(Thread.currentThread().getId()+"释放了lock,结束休息");lock.unlock();//最后一定要释放锁}}}

?

?

然后使用java的synchronized关键字实现加锁:

?

?

package com.tch.test.concurrent;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class SynchronizedTest {private ExecutorService pool = Executors.newFixedThreadPool(4);//private Lock lock = new ReentrantLock();private Object obj = new Object();public static void main(String[] args) {new SynchronizedTest().test();}public void test() {Runnable runnable = null;for(int i=0;i<4;i++){runnable = new Runnable(){public void run(){while(true){execute();}}};pool.execute(runnable);}}void execute(){synchronized(obj){try {System.out.println(Thread.currentThread().getId()+"获得了obj的锁,开始休息");Thread.sleep(300);System.out.println(Thread.currentThread().getId()+"释放了obj的锁,结束休息");} catch (InterruptedException e) {e.printStackTrace();}}}}

?

?

?

?

?

Thread-1:synchronized in g()

?

读书人网 >编程

热点推荐