1.实现两个线程交替打印0--100的奇偶数:
线程类:
public class OddEvenThread implements Runnable {
private Object obj;
private volatile int count;
public OddEvenThread(Object oj, int count){
this.obj=oj;
this.count=count;
}
@Override
public void run() {
while(count<=100){
synchronized (obj){
try {
System.out.println(Thread.currentThread().getName()+":"+count);
count++;
obj.notify();
if(count<=100){
obj.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
测试类:
public class mian { public static void main(String args[]) throws InterruptedException { Object oj=new Object(); int i=0; OddEvenThread runable=new OddEvenThread(oj,i); Thread threa01=new Thread(runable,"偶数"); //确保偶数线程选执行 Thread.sleep(2000); Thread thread02=new Thread(runable,"奇数"); threa01.start(); thread02.start(); } }