方法一
使用synchronized关键字配合奇偶数的判断实现
public class SystemOddEven1 {
private static int count = 0;
private static final Object object = new Object();
public static void main(String[] args) {
SystemEven even = new SystemEven("偶数线程");
SystemOdd odd = new SystemOdd("奇数线程");
even.start();
odd.start();
}
//打印奇数
static class SystemOdd extends Thread{
public SystemOdd(){
}
public SystemOdd(String name){
super(name);
}
@Override
public void run() {
while (SystemOddEven1.count<100){
synchronized (object){
if (count%2==1){
System.out.println(Thread.currentThread().getName()+":"+count++);
}
}
}
}
}
//打印偶数
static class SystemEven extends Thread{
public SystemEven(){
}
public SystemEven(String name){
super(name);
}
@Override
public void run() {
while (SystemOddEven1.count<=100){
synchronized (object){
if (count%2==0){
System.out.println(Thread.currentThread().getName()+":"+count++);
}
}
}
}
}
}
方法二
使用synchronized关键字配合wait和notify实现
public class SystemOddEven2 {
private static int count = 0;
private static final Object object =new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(new SystemNum(),"偶数线程");
Thread thread2 = new Thread(new SystemNum(),"奇数线程");
thread1.start();
thread2.start();
}
//打印奇数
static class SystemNum implements Runnable{
@Override
public void run() {
while (count<=100){
synchronized (object){
System.out.println(Thread.currentThread().getName()+":"+count++);
object.notify();//唤醒另一个线程
if (count<=100){
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}