• 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;
                       }
            
        }
        
    }
  • 相关阅读:
    定时任务框架APScheduler学习详解
    Python list 和 str 互转
    python多个变量赋值
    python数据类型转换
    jquery datetimepicker 配置参数
    c#判断是否为合法的email地址
    SQL的四种连接-左外连接、右外连接、内连接、全连接
    SQL表连接查询(inner join、full join、left join、right join)
    简单的日期转换
    递归
  • 原文地址:https://www.cnblogs.com/zywf/p/4714504.html
Copyright © 2020-2023  润新知