zoukankan      html  css  js  c++  java
  • java中使用wait就得使用同步锁,而且2个线程必须都使用同步代码块,否则就会异常

    标题已经说明,子线程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();
    					}
    			}
    		}
    	}
    	
    }
    
    }
    

      

  • 相关阅读:
    Nginx 和 PHP的安装配置
    hdu1166 敌兵布阵
    乘法逆元详解
    SPFA算法
    Kruskal算法&Prim算法
    WC2018 文艺汇演《退役的你》
    HDU2577 How to Type
    裴蜀定理的证明
    CSP J/S 2019受虐记
    Dijkstra算法详解
  • 原文地址:https://www.cnblogs.com/bokeofzp/p/4762248.html
Copyright © 2011-2022 走看看