多线程一个线程打印奇数,一个线程打印偶数:

那么需要使用同步锁,当一个线程a获取到锁,另一个线程b只能阻塞,然后a打印res(奇数),然后就需要让b线程去打印,而b线程处于阻塞,那么需要通过调用锁对象的notify(),唤醒一个在该锁对象下的阻塞的一个线程,但是如果a线程继续运行退出代码块后,会和b线程继续竞争锁,那么就需要使用wait()方法,将线程a挂起,并释放锁,此时线程b获取到锁之后就可以打印res(偶数),然后重复上面的操作。
特别的,最后一个线程调用wait()挂起自己后,由于没有别的线程来唤醒这个线程,就会导致程序无法结束,那么需要判断当前线程是否是最后一个,不是最后一个才挂起。
public class Main {
static Object distan = new Object();
static int res = 1;
static int cnt1= 100;
static int cnt2= 100;
public static void main(String[] args) throws IOException, InterruptedException {
Thread thread1=new Thread(new Runnable() {
@Override
public void run() {
while(cnt1-->0){
synchronized (distan) {
System.out.println(Thread.currentThread().getName()+":"+res++);
distan.notify();
try {
if(cnt1!=0)
distan.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
});
Thread thread2=new Thread(new Runnable() {
@Override
public void run() {
while(cnt2-->0){
synchronized (distan) {
System.out.println(Thread.currentThread().getName()+":"+res++);
distan.notify();
try {
if(cnt2!=0)
distan.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
});
thread1.start();
thread2.start();
}
}