I got it interview that:
Thread-A Prints Even numbers from 0
Thread-B prints Odd numbers from 1
I want to print 0 1 2 3 4.... in natural order till 1000 How can I achive.
I tried this way:
public class ThreadDemo2 {
static int aa = 0;
public static void main(String[] args) {
boolean mytime = true;
EvenThread et = new EvenThread(mytime);
OddThread ot = new OddThread(mytime);
et.start();
ot.start();
}
}
class EvenThread extends Thread {
boolean mytime;
int i = 0;
public EvenThread(boolean mytime) {
this.mytime = mytime;
}
public void run() {
//if (ThreadDemo2.aa == 0) {
for (int i = 0; i < 1000 && ThreadDemo2.aa == 0; i += 2) {
System.out.println(i);
ThreadDemo2.aa = 1;
try {
sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// }
}/* else
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
class OddThread extends Thread {
boolean mytime;
int i = 1;
public OddThread(boolean mytime) {
this.mytime = mytime;
}
public void run() {
//if (ThreadDemo2.aa == 1) {
for (int i = 1; i < 1000 && ThreadDemo2.aa == 1; i += 2) {
System.out.println(i);
ThreadDemo2.aa = 0;
try {
sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//ThreadDemo2.aa = 0;
//}
}
}
Unfortunately you can't expect the result because of JVM working on 2 different threads , but you can do something like that,
public class Test12 {
public static void main(String[] args) {
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
}
}
class Thread1 implements Runnable {
public Thread1() {
Thread t = new Thread();
t.start();
}
@Override
public void run() {
try {
for (int i = 0; i < 1000; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
} catch (Exception e) {
}
}
}
class Thread2 implements Runnable {
public Thread2() {
Thread t = new Thread(this);
t.start();
}
@Override
public void run() {
try {
for (int i = 0; i < 1000; i++) {
if (i % 2 == 1) {
System.out.println(i);
}
}
} catch (Exception e) {
}
}
}
when you run this application many times, you will notice that there are no result like other 100%