6
See the execution of two similar programs in Java. One inherits from Thread
and another implements the interface Runnable
:
Program1:
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:
And we have program 2:
public class PingPong2 implements Runnable{
private String msg;
private int delay;
PingPong2(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) {
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:
Why the output on program1 is not printed "ping1" since in the method implementation run()
, the print on the screen is made before placing the thread to sleep (on hold)?
Did the answer solve your problem? Do you think you can accept it? If you don’t know how you do it, check out [tour]. This would help a lot to indicate that the solution was useful to you and to give an indication that there was a satisfactory solution. You can also vote on any question or answer you find useful on the entire site.
– Maniero