Codul sursă al aplicațieiimport java.applet.*; /* Clasa Machine implementează comportamentul dorit de programator pentru un Thread */ class Machine extends Thread{ protected int initial_value; protected int counter=0; protected int x_draw; //coordonatele de unde se începe protected int y_draw; // scrierea textului public Machine(int i, int x, int y){ initial_value=i; x_draw=x; y_draw=y; } public void run(){ while(true){ try {Thread.sleep(150);} catch(InterruptedException e){ System.out.println("There is an Interrupt edException"); } counter=(initial_value++)%10; } } } public class game extends Applet implements Runnable{ protected Machine first_machine; protected Machine second_machine; protected Machine third_machine; Thread engine=null; protected Random r =new Random(); Button first_button = new Button("first"); Button second_button = new Button("second"); Button third_button = new Button("third"); public void init(){ resize(400,100); add(first_button); add(second_button); add(third_button); // generarea valorilor inițiale de start pentru counter int i1=Math.abs(r.nextInt()%10); int i2=Math.abs(r.nextInt()%10); int i3=Math.abs(r.nextInt()%10); first_machine=new Machine(i1, 140,50); second_machine=new Machine(i2,190,50); third_machine=new Machine(i3,244,50); } public boolean action(Event e, Object o){ if(e.target instanceof Button){ if("first".equals((String)o)) { first_machine.stop(); return true; } if( "second".equals((String)o)) { second_machine.stop(); return true; } if("third".equals((String)o)) { third_machine.stop(); return true; } } return false; } public void start(){ if (engine = = null){ engine=new Thread(this); first_machine.start(); second_machine.start(); third_machine.start(); engine.start(); } } public void run(){ while ((first_machine.isAlive()) || (second_machine.isAlive()) || (third_machine.isAlive())) { try{Thread.sleep(150);} catch(InterruptedException e){} repaint(); } } public void paint(Graphics g){ g.drawString(String.valueOf(first_machine.counter), first_machine.x_draw,first_machine.y_draw); g.drawString(String.valueOf(second_machine.counter), second_machine.x_draw,second_machine.y_draw); g.drawString(String.valueOf(third_machine.counter), third_machine.x_draw,third_machine.y_draw); } } Programarea multithreading în JavaBYTE România - noiembrie 1997
(C) Copyright Computer Press Agora |