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;
                   }
        
    }
    
}

 

posted @ 2015-08-09 07:50  自由无风  阅读(426)  评论(0编辑  收藏  举报