+ 3
Can someone explain how to create a thread in java with a sample code ?
6 Réponses
+ 7
Wow that is an awesome crystal clear explanation @Juliano Ventola
+ 3
package threads;
//Every program that uses threads must implement the Runnable class
public class PingPongRunnable implements Runnable{
String word;
long time;
//Constructor of class, here we will pass the word we will print and how many time
//it will wait
public PingPongRunnable(String p, long tempo){
this.word = p;
this.time = tempo;
}
public static void main(String[] args) {
//creat 2 runnable objects, one with the word "ping" and it will wait 1s(1000 = 1second)
//The other objetct "pong" will wait 2s to run again
Runnable ping = new PingPongRunnable("ping",1500);
Runnable pong = new PingPongRunnable("pong",2000);
//Here we ask to run both runnable objects at the SAME TIME, the program wont wait
//to run "ping" finish the 15 times
new Thread(ping, "ping").start();
new Thread(pong, "pong").start();
}
//When u implement a runnable class u must Override the run method
@Override
public void run() {
//The system will try to run this 15 times
try {
for (int i = 0; i < 15; i++) {
//Print the word
System.out.println(word);
//The time to sleep, to wait to run again
Thread.sleep(time);}
} catch (InterruptedException e) {
// if u get an error, will print here!
e.printStackTrace();
}
return;
}
}
+ 2
Thank you very much for explaination @Juliano
+ 2
thank you @sami
0
u can copy and paste to run ;)