import lombok.Data;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 两个线程,按顺序打印单双数
*/
public class test {
public static AtomicInteger obj = new AtomicInteger(0);
public static void main(String[] args) {
thread_my t1 = new thread_my(obj, 0, 0);
thread_my t2 = new thread_my(obj, 1, 1);
t1.start();
t2.start();
}
@Data
static class thread_my extends Thread {
private AtomicInteger cur;
private int out;
private int flag;
private int count = 0;
thread_my(AtomicInteger cur, int out, int flag) {
this.cur = cur;
this.out = out;
this.flag = flag;
}
public void run() {
for (int i = 0; i < 5; i++) {
while(true){
synchronized (obj) {
if (cur.get() % 2 == flag) {
System.out.println(out);
out += 2;
cur.set(cur.get() + 1);
cur.notifyAll();
break;
}else{
try {
obj.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
}
}