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