TaskThread extends Thread { public long getResult() { synchronized (monitor) { logger.finest( Thread.currentThread().getName() + " enters " + this.getName() + " getResult(), monitor = " + monitor); while (!isReady) { try { logger.finest( Thread.currentThread().getName() + " waits for " + monitor); monitor.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } logger.finest(Thread.currentThread().getName() + " quits " + this.getName() + " getResult()"); return result; } } TaskThread(int id, TaskParam a, TaskParam b, TaskParam p, TaskParam m, long n); @Override void run(); long getResult(); final TaskParam a; final TaskParam b; final TaskParam p; final TaskParam m; final long n; }
@Test public void test1() { System.out.println(); System.out.println(); final TaskThread task1 = BuildTask(101, 102, 103, 1041, 205); final TaskThread task2 = BuildTask(1, 2, 1, 4, 0); final TaskThread task3 = BuildTask(task1, 12, 1, 100, 10); final TaskThread task4 = BuildTask(task1, 13, 1, 100, 10); final TaskThread task5 = BuildTask(task1, 14, 1, 100, 10); Thread printer = new Thread(() -> { System.out.println("result: " + task1.getResult()); System.out.println("result: " + task2.getResult()); System.out.println("result: " + task3.getResult()); System.out.println("result: " + task4.getResult()); System.out.println("result: " + task5.getResult()); }); printer.start(); task3.start(); task5.start(); task1.start(); task2.start(); task4.start(); }