zoukankan      html  css  js  c++  java
  • java多线层同时运行的解决,同步代码块synchronized

    /*
    多个线层同时操作一个数据
    会导制数据超出
    同步代码块
    synchronized(对像)
    {
    需要同步的代码
    }
    */
    
    class Do7 
    {
        public static void main(String[] args) 
        {
                Piao p1=new Piao();
                Thread t1=new Thread(p1);
                Thread t2=new Thread(p1);
                Thread t3=new Thread(p1);
                Thread t4=new Thread(p1);
                t1.start();t2.start();t3.start();t4.start();
        }
    }
    
    class Piao implements Runnable
    {
        private  static int num=200;
      
        public void run()
        {
    
            while(true)
            {
                //  Object obj=new Object();//随便创建一个对象,用于synchronized(对像)
                // synchronized(this)中可以放this,也可以放synchronized(obj)
             synchronized(this)///同步代码块
            {
            if (num>0)
            {
                try{Thread.sleep(10);}catch(Exception e){}
                System.out.println(Thread.currentThread().getName()+"....."+num--);
            }
            else{
            return;}
    }
            }
        }
    }

     第二种方式

    /*
    多个线层同时操作一个数据
    会导制数据超出
    同步代码块
    synchronized(对像)
    {
    需要同步的代码
    }
    */
    
    class Do7 
    {
        public static void main(String[] args) 
        {
                Piao p1=new Piao();
                Thread t1=new Thread(p1);
                Thread t2=new Thread(p1);
                Thread t3=new Thread(p1);
                Thread t4=new Thread(p1);
                t1.start();t2.start();t3.start();t4.start();
        }
    }
    
    class Piao implements Runnable
    {
        private int num=100;
        public void run()
        {
            while(true)
            {
             show();
            }
        }
        public synchronized void show()
        {
            
                    if (num>0)
                     {
                     try{Thread.sleep(10);}catch(Exception e){}
                     System.out.println(Thread.currentThread().getName()+"....."+num--);
                    }
                      else{
                     return;
                       }
            
        }
        
    }
  • 相关阅读:
    python程序设计练习题:电子银行购物商城
    python -m参数
    Python 中的 if __name__ == 'main' 的作用和原理
    Modbus协议
    Python configparser模块
    Python logging 模块:日志处理
    python hashlib模块
    Python time模块:Python 日期和时间
    mac 使用系统的自带的quickTime录屏
    Linphone android3.2.4 采用率设置(模拟电话大网信道)
  • 原文地址:https://www.cnblogs.com/zywf/p/4714504.html
Copyright © 2011-2022 走看看