public class ThreadTest {
// public static int i = 0;
private static final Object lock = new Object();//锁
public static class Thread1 extends Thread{
@Override
public void run(){
for (int i = 0; i <=100; i = i+2) {
synchronized (lock){
lock.notify();//唤醒,获取锁
System.out.println(Thread.currentThread().getName()+" "+i);
try{
lock.wait();//打印之后等待,释放锁,t2拿到锁开始工作
}catch (Exception e){
e.getLocalizedMessage();
}
}
}
}
}
public static class Thread2 extends Thread{
@Override
public void run(){
for (int i = 1; i <=100; i = i+2) {
synchronized (lock){
lock.notify();
System.out.println(Thread.currentThread().getName()+" "+i);
try{
lock.wait();//打印之后等待
}catch (Exception e){
e.getLocalizedMessage();
}
}
}
}

@Test
public void Test(){
try {
new Thread1().start();
new Thread2().start();
Thread.sleep(200);//这里不加sleep在IDEA中运行可能会造成程序提前结束打印不全
}catch (Exception e){
e.getLocalizedMessage();
}
}
}
}