Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class Task extends Thread{
- private int result;
- private final Lock computeLock = new ReentrantLock();
- private boolean computed = false;
- private final Condition canGet = computeLock.newCondition();
- private int compute() {
- int val;
- val = 543;
- return val;
- }
- public int getResult() {
- computeLock.lock();
- try {
- while (!computed) {
- try {
- canGet.await();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- return result;
- } finally {
- computeLock.unlock();
- }
- }
- public void run() {
- computeLock.lock();
- try {
- result = compute();
- computed = true;
- canGet.signalAll();
- } finally {
- computeLock.unlock();
- }
- }
- }
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.TimeUnit;
- public class TestMe {
- /**
- * @param args
- */
- public static void main(String[] args) {
- while (true) {
- Task task1 = new Task();
- Task task2 = new Task();
- ExecutorService threadExecutor = Executors.newCachedThreadPool();
- threadExecutor.execute(task1);
- threadExecutor.execute(task2);
- threadExecutor.shutdown();
- System.out.println("result = " + (task1.getResult() + task2.getResult()));
- try {
- threadExecutor.awaitTermination(1, TimeUnit.DAYS);
- } catch (InterruptedException ex) {
- System.err.println("Something bad happened: " + ex.getMessage());
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement