public class EvenOddWithTwoThreads **extends Thread**
{
private volatile int count = 1;
private volatile boolean flag = false;
@Override
public void run() {
while(count <=10){
synchronized (this) {
while(flag){
flag= false;
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() +count);
count= count+1;
flag = true;
notify();
}
}
}
public static void main(String[] args) {
EvenOddWithTwoThreads ins = new EvenOddWithTwoThreads();
**Thread t1 = new Thread(ins, "Odd Thread");**
**Thread t2 = new Thread(ins,"Even Thread");**
t1.start();
t2.start();
}
}
奇線程1
奇線程2
奇Thread3
即使Thread4
奇Thread5
偶Thread6
奇數Thread7
即使Thread8
奇數Thread9
即使Thread10
public class EvenOddWithTwoThreads **implements Runnable**{
private volatile int count = 1;
private volatile boolean flag = false;
@Override
public void run() {
while(count <=10){
synchronized (this) {
while(flag){
flag= false;
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() +count);
count= count+1;
flag = true;
notify();
}
}
}
public static void main(String[] args) {
EvenOddWithTwoThreads ins = new EvenOddWithTwoThreads();
Thread t1 = new Thread(ins, "Odd Thread");
Thread t2 = new Thread(ins,"Even Thread");
t1.start();
t2.start();
}
}
輸出:
奇線程1
即使線程2
奇Thread3
即使Thread4
奇Thread5
即使Thread6
奇Thread7
即使Thread8
奇Thread9
即使Thread10
check [this](http://stackoverflow.com/questions/541487/implements-runnable-vs-extends-thread)。 – Null