See the execution of two similar programs in Java. One inherits from Thread
and another implements the interface Runnable
:
Program 1:
public class PingPong extends Thread{
private String msg;
private int delay;
PingPong(String s,int tempo){
msg = s;
delay = tempo;
}
public void run(){
try{
for (int i=1;i<=10;i++){
System.out.println(msg+ " " + i);
Thread.sleep(delay);
}
}
catch (Exception e){
System.err.println("Deu pau!");
return;
}
}
public static void main(String[] args) {
PingPong ping = new PingPong("ping",500);
ping.start();
PingPong pong = new PingPong("pong",1000);
pong.start();
System.out.println("*** FIM DO PROGRAMA PRINCIPAL ***");
}}
It generates the following output:
Andwehaveprogram2:
publicclassPingPong2implementsRunnable{privateStringmsg;privateintdelay;PingPong2(Strings,inttempo){msg=s;delay=tempo;}publicvoidrun(){try{for(inti=1;i<=10;i++){System.out.println(msg+" " + i);
Thread.sleep(delay);
}
}
catch (Exception e){
System.err.println("Deu pau!");
return;
}
}
public static void main(String[] args) {
Runnable ping = new PingPong2("ping",500);
Runnable pong = new PingPong2("pong",1000);
new Thread(ping).start();
new Thread(pong).start();
System.out.println("*** FIM DO PROGRAMA PRINCIPAL ***");
}
}
Generating the following output:
Becausetheoutputinprogram1doesnotprint"ping1" because in the implementation of the run()
method, on-screen printing is done before putting the thread to sleep )?