package com
.sgg
.thread
;
public class ThreadTest03 {
public static class Handler {
public int value
= 1;
public boolean odd
= true;
}
public static Handler handler
= new Handler();
public static class PrintOdd implements Runnable {
@Override
public void run() {
while (handler
.value
<= 100) {
synchronized (handler
) {
if (handler
.odd
) {
System
.out
.println(Thread
.currentThread().getName() + "-->" + handler
.value
);
handler
.value
++;
handler
.odd
= !handler
.odd
;
handler
.notify();
} else {
try {
handler
.wait();
} catch (InterruptedException e
) {
e
.printStackTrace();
}
}
}
}
}
}
public static class PrintEven implements Runnable {
@Override
public void run() {
while (handler
.value
<= 100) {
synchronized (handler
) {
if(handler
.odd
){
try {
handler
.wait();
} catch (InterruptedException e
) {
e
.printStackTrace();
}
}
else {
System
.out
.println(Thread
.currentThread().getName() + "-->" + handler
.value
);
handler
.value
++;
handler
.odd
= !handler
.odd
;
handler
.notify();
}
}
}
}
}
public static void main(String
[] args
) {
Thread oddThread
= new Thread(new PrintOdd());
Thread evenThread
= new Thread(new PrintEven());
oddThread
.setName("oddThread");
evenThread
.setName("evenThread");
oddThread
.start();
evenThread
.start();
}
}
输出结果:
转载请注明原文地址: https://lol.8miu.com/read-6822.html