/* * Proposed solution for CP Lab 1, step 8 */ import java.awt.*; class Task extends Thread { TextField tf; public Task(TextField t) { tf = t; } public void run () { long delay = (Math.round(Math.random()*12)+4)*1000/tf.getColumns(); boolean useCPU = true; // Set true to consume CPU-cycles String s = ""; tf.setText(s); while (s.length() < tf.getColumns()) { if (interrupted()) break; if (useCPU){ for (int j = 0; j < 100000*delay; j++) {} } else { try { Thread.sleep(delay); } catch (InterruptedException e) {break;} } s = s + "#"; tf.setText(s); } if (s.length() < tf.getColumns()) {s = s + "|"; tf.setText(s);} } } public class TaskControl_8 { static final int N = 5; // Number of Textfields static int h = 0; // Number of 'hello'-s public static void main(String[] argv) { try { // Create window with 'N' TextFields: (d.tf[0], ... , d.tf[N-1]) TaskDisplay d = new TaskDisplay("Task Control", N); Task[] task = new Task[N]; d.println("Type command (x to exit):"); W: while (true) { // Main command interpretation loop char c = d.getKey(); switch (c) { case 'x': break W; case 'h': d.println("Hello " + (h++)); break; case 't': int i = 0; while (i < 5) { if (task[i] == null || !task[i].isAlive()) { task[i] = new Task(d.tf[i]); task[i].start(); break; } i++; } if (i==5) d.println("No free text-fields"); break; case '0': case '1': case '2': case '3': case '4': int j = ((int) c) - ((int) '0'); if (task[j] != null) task[j].interrupt(); break; default: d.println("Don't know '" + c + "'"); } } d.println("Program terminates"); for (int i = 0; i<5; i++) { if (task[i] != null) task[i].join(); } System.exit(0); } catch (Exception e) {System.out.println("Task Control: " + e); } } }