-------------------synchronized不生效--------------- public class tx implements Runnable{ static Integer a=new Integer(0); static int i=0; public void increase(){ Integer integer = new Integer(0); synchronized(integer){ i++;} } @Override public void run(){ for (int j =0 ; j<10000;j++){ increase(); } } public static void main(String[] args) throws InterruptedException { tx tx = new tx(); Thread t1 = new Thread(tx); Thread t2 = new Thread(tx); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(i); } ----------------分割线(synchronized生效)--------------------- public class tx implements Runnable{ static Integer a=new Integer(0); static int i=0; Integer integer = new Integer(0);---》放入increase方法内定义不生效 public void increase(){ synchronized(integer){ i++;} } @Override public void run(){ for (int j =0 ; j<10000;j++){ increase(); } } public static void main(String[] args) throws InterruptedException { tx tx = new tx(); Thread t1 = new Thread(tx); Thread t2 = new Thread(tx); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(i); }
两个线程使用的是两个不同的锁,线程之间没有相互影响。
public void increase(){ Integer integer = new Integer(0); synchronized(integer){ i++;} } @Override public void run(){ for (int j =0 ; j<10000;j++){ increase(); } }
这样写每次执行run方法锁都不一样。