标题已经说明,子线程wai()时候默认的锁不是同步代码块的锁,因此wai时候显示的指明锁,现在解释看code:
public class Test { // static boolean flag=true; public static void main(String[] args) throws InterruptedException { Zp z=new Zp(); Thread st=new Thread(z); st.start(); for(int x=0;x<100000;x++) { if(x%5000==0) { // flag=false; Thread.sleep(3000); synchronized (Test.class) //这里必须判断锁,否则当子线程没有放弃锁的时候,就执行下面会出现异常 { Test.class.notify(); } } } } static class Zp implements Runnable { @Override public void run() { synchronized (Test.class) { while(true) { for(int x=0;x<10;x++) { System.out.println("haha..."); } try { Test.class.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }