???????
????应付面试:面试管一般会问有过线程没有,你会在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); } }
?