Write a program using threads which prints the following:
In first thread:0
In Second Thread:0
In Second Thread:1
In first thread:1
In Second Thread:2
In Second Thread:3
In first thread:2
In Second Thread:4
In Second Thread:5
In first thread:3
In Second Thread:6
In Second Thread:7
In first thread:4
In Second Thread:8
In Second Thread:9
End of first thread
End of second thread
In first thread:0
In Second Thread:0
In Second Thread:1
In first thread:1
In Second Thread:2
In Second Thread:3
In first thread:2
In Second Thread:4
In Second Thread:5
In first thread:3
In Second Thread:6
In Second Thread:7
In first thread:4
In Second Thread:8
In Second Thread:9
End of first thread
End of second thread
SOLUTION:
public class ThreadExample {
public static void main(String args[]){
//Creating the thread class object
ThreadB targetb=new ThreadB();
ThreadC targetc=new ThreadC();
//Creating the threads
Thread one = new Thread(targetb," First Thread");
Thread two = new Thread(targetc," Second Thread");
//Starting the threads
one.start();
two.start();
}
}
class ThreadB extends Thread {
public void run(){
for ( int i=0; i < 5; i++ ) {
try {
sleep(200);
}
catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
System.out.println(i+""+Thread.currentThread().getName());
}
System.out.println("End of first thread.");
}
}
class ThreadC extends Thread {
public void run() {
for( int i=0; i < 10; i++ ) {
try {
sleep(100);
}
catch (InterruptedException interruptedException) {
interruptedException.printStackTrace();
}
System.out.println(i+""+Thread.currentThread().getName());
}
System.out.println("End of Second Thread.");
}
}
No comments:
Post a Comment