标签:
/* 多个线层同时操作一个数据 会导制数据超出 同步代码块 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=100; Object obj=new Object();//随便创建一个对象,用于synchronized(对像) public void run() { while(true) { synchronized(obj)///同步代码块 { if (num>0) { try{Thread.sleep(10);}catch(Exception e){} System.out.println(Thread.currentThread().getName()+"....."+num--); } else{ return;} } } } }
java多线层同时运行的解决,同步代码块synchronized
标签:
原文地址:http://www.cnblogs.com/zywf/p/4714504.html