面试题:两个线程交替输出1-10
不知道wait()和notify()一定要在synchronized里,面试写的代码惨不忍睹
public class Main {
private volatile int count = 1;
/**
* 输出奇数
*/
public void print1() {
try {
while (count<=9) {
synchronized (this){
if(count%2==0){
this.wait();
}
System.out.println(count++);
this.notify();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 输出偶数
*/
public synchronized void print2() {
try {
while (count<=10) {
synchronized (this){
if(count%2==1){
this.wait();
}
System.out.println(count++);
this.notify();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Main main = new Main();
new Thread(main::print1).start();
new Thread(main::print2).start();
}
}
最初想用Atomic包,忘了包名,然后面试官让用wait和notify,结果不会
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) {
AtomicInteger integer=new AtomicInteger(1);
new Thread(() -> {
while (integer.get()<=9){
if(integer.get()%2==1){
System.out.println(integer.get());
integer.incrementAndGet();
}
}
}).start();
new Thread(() -> {
while (integer.get()<=10){
if(integer.get()%2==0){
System.out.println(integer.get());
integer.incrementAndGet();
}
}
}).start();
}
}