I'm learning Java's multithreading and now trying following:
I'd like to have two threads, thread A prints odd numbers only, thread B prints even number only.
When thread A finishs output a number, it tells B: "it is your turn to print", vice versa. In C++ I use semaphore for such things, but I don't know how to do it in Java.
Here is my code:
class printer {
int i;
void say() {
System.out.println(i++);
}
}
class p1 extends printer implements Runnable {
public void run() {
while (true) {
//waitP2();
say();
//tellP2();
try {
Thread.sleep(1);
} catch (InterruptedException e) {}
}
}
}
class p2 extends printer implements Runnable {
public void run() {
while (true) {
//waitP1();
say();
//tellP1();
try {
Thread.sleep(1);
} catch (InterruptedException e) {}
}
}
}
public class a {
public static void main(String[] args) {
Thread t1 = new Thread(new p1());
Thread t2 = new Thread(new p2());
t1.start(); t2.start();
try {
t1.join(); t2.join();
} catch (InterruptedException e) {}
}
}