Can someone explain how to create a thread in java with a sample code ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Can someone explain how to create a thread in java with a sample code ?

16th Jun 2017, 6:37 AM
Doolitha Samaranayake
Doolitha Samaranayake - avatar
6 Answers
+ 7
Wow that is an awesome crystal clear explanation @Juliano Ventola
16th Jun 2017, 7:39 AM
Sri Lakshmi
Sri Lakshmi - avatar
+ 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; } }
16th Jun 2017, 6:57 AM
Juliano Ventola
Juliano Ventola - avatar
16th Jun 2017, 9:54 AM
Мг. Кнап🌠
Мг. Кнап🌠 - avatar
+ 2
Thank you very much for explaination @Juliano
17th Jun 2017, 4:08 AM
Doolitha Samaranayake
Doolitha Samaranayake - avatar
+ 2
thank you @sami
17th Jun 2017, 4:08 AM
Doolitha Samaranayake
Doolitha Samaranayake - avatar
0
u can copy and paste to run ;)
16th Jun 2017, 6:57 AM
Juliano Ventola
Juliano Ventola - avatar