首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

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

2013-10-01 
使用synchronized和Lock对象获取对象锁package com.tch.test.concurrentimport java.util.concurrent.Exe

使用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()

?

热点排行