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;
                       }
            
        }
        
    }
  • 相关阅读:
    一天一个Linux命令--find
    一天一个Linux命令--dhclient
    一道CTF题引发的思考——SSI注入
    netcat的简单使用(一)
    文件头类型
    windows10禁用更新方法
    Burpsuite 之intruder
    localstorage sessionstorage和cookie的区别
    js中的迭代方法-every, some, filter, map, forEach
    前端日志分类
  • 原文地址:https://www.cnblogs.com/zywf/p/4714504.html
Copyright © 2011-2022 走看看