Multi Threading
public class MultiThreading implements Runnable {
static Thread t1, t2;
public static void main(String[] args) {
t1 = new Thread(new MultiThreading()); //Declares two threads in class MultiThreading
t2 = new Thread(new MultiThreading());
System.out.println("Thread 1 started");
t1.start(); // Thread 1 is started and run method is executed
System.out.println("Thread 2 started");
t2.start(); // Thread 2 is started and run method is executed
}
public void run() { // Run is executed for two threads
if (Thread.currentThread() == t1) { // Checks which is the current thread
for(int i=0;i<5;i++){ // Thread t1 is assigned the task of displaying values from 1 to 5
try {
System.out.println(i);
Thread.sleep(1000); // Delays the execution of thread for 1000 milliseconds
} catch (InterruptedException ex) {
Logger.getLogger(MultiThreading.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
if(Thread.currentThread()==t2){ // Checks whether the current thread is t2
for(int i=100;i>95;i--){ // Thread t2 is assigned the task of displaying values from 100 to 95
try {
System.out.println(i);
Thread.sleep(1000); // Delays the execution of thread for 1000 milliseconds
} catch (InterruptedException ex) {
Logger.getLogger(MultiThreading.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
Output:
Thread 1 started
Thread 2 started
0
100
1
99
2
98
3
97
96
4