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
でもThread4
でもThread6
奇数Thread7
でもThread8奇数Thread5
でもスレッド2
奇数Thread3
奇数Thread9
でもThread10
check [this](http://stackoverflow.com/questions/541487/implements-runnable-vs-extends-thread) – Null