Lock java synchronized sendlockCondition.await sendlockCondition.signal();_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Lock java synchronized sendlockCondition.await sendlockCondition.signal();

Lock java synchronized sendlockCondition.await sendlockCondition.signal();

 2014/9/7 18:19:13  knight_black_bob  程序员俱乐部  我要评论(0)
  • 摘要:应付面试:面试管一般会问有过线程没有,你会在A的线程里面获取B线程的数据吗?见图:(图1)1.创建一个缓存池,用于线程管理packagetest20140907.testthread3;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.concurrent.Future;publicclassThreadPool{privateThreadPool(){
  • 标签:Java Ron

???????

????应付面试:面试管一般会问有过线程没有,你会在A的线程里面获取B线程的数据吗?

???

???? 见图:(图1)

?

?1.创建一个缓存池,用于线程管理

class="ThreadPool ">package test20140907.testthread3;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadPool {

	private ThreadPool() {
	}
	private static ThreadPool instance;
	public static ThreadPool getInstance() {
		if (instance == null) {
			instance = new ThreadPool();
		}
		return instance;
	}

	
	@SuppressWarnings("rawtypes")
	static Future future =null;
	static ExecutorService cachedService;

	public void init() {
		cachedService = Executors.newFixedThreadPool(1);
		cachedService.execute(new RunableA());
	}
	class RunableA implements Runnable {

		@Override
		public void run() {
			TaskFirst tf =new TaskFirst();
			tf.getValue();
		}

	}
	
}

?

?

?

?

?2.任务下发

package test20140907.testthread3;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TaskFirst {

	
	static double d;

	Lock sendlock = new ReentrantLock();
	Condition sendlockCondition =sendlock.newCondition();
	
	
	public void addValue(double doub){
		sendlock.lock();
		try {
			sendlockCondition.await(5,TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("getValue d: "+ d);
		sendlock.unlock();
	}
	
	public void getValue(){
		sendlock.lock();
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		this.d= 5.5;
		System.out.println("addValue d: "+ d);
		sendlockCondition.signal();
		sendlock.unlock();
	}

}

?

?

3.测试? 模拟一个执行任务的线程获取数据,该线程犹如网络延迟耗费3s 然后接收任务的线程等待5s 获取数据 完成一次同步的通讯

package test20140907.testthread3;

public class Test {


	public static void main(String[] args) {
		ThreadPool.getInstance().init();
		TaskFirst tf =new TaskFirst();
		tf.addValue(2);
		
	}

}

?

  • 描述: 运行结果
  • 大小: 10.8 KB
  • 查看图片附件
上一篇: 科技大拿开什么车? 下一篇: 没有下一篇了!
发表评论
用户名: 匿名