Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

CSE 1007

2. Write an application that executes two threads. One thread displays Even
numbers every 1000 milliseconds and another thread displays odd
numbers every 3000 milliseconds. Create the threads by implementing
the Runnable interface
[use start, run, sleep, join, isAlive, getName and setName methods]CODE:-
class EvenThread implements Runnable{
private int max;
public EvenThread(int max){
this.max=max;
}
public void run() {
for(int i=0;i<max;i++){
if(i%2==0){
System.out.println(i);
}
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class OddThread implements Runnable {
private int max;
public OddThread(int max){
this.max=max;
}
public void run() {
for(int i=0;i<max;i++){
if(i%2!=0){
System.out.println(i);
}
try {
Thread.currentThread().sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class ThreadTest {
public static void main(String[] args) {
EvenThread even=new EvenThread(100);
Thread t1 =new Thread(even);
OddThread odd= new OddThread(100);Thread t2=new Thread(odd);
t1.start();
System.out.println("IS T1 ALIVE?"+t1.isAlive());
System.out.println("THREAD ID:" + t1.getId());try{
t1.join();
}
catch(Exception e){}
t2.start();
System.out.println("IS T2 ALIVE? "+t2.isAlive());
System.out.println("THREAD ID:" + t2.getId());
t1.setName("Thread to print even numbers");
t2.setName("Thread to print odd numbers");
System.out.println("THREAD1 NAME: "+t1.getName());
System.out.println("THREAD2 NAME: "+t2.getName());
}
}

You might also like