synchronized提供了一种锁的机制,能够确保共享变量之间的互斥访问,从而防止数据不一致问题的出现
synchronized关键字包括monitor enter和monitor exit两个jvm指令,他们是成对出现的,他能够保证在任何时候任何线程执行到monitor enter成功之前都必须从主内存中获取数据,而不是从缓存中,在monitor exit运行成功之后,共享变量被更新后的值必须刷入主内存。
synchronized ,一个monitor exit 指令之前必定要有一个monitor enter
他的实现有多种方式:
第一种:同步方法
public class SyncClass implements Runnable{
private int index=1;
@Override
public synchronized void run() {
System.out.println(Thread.currentThread()+"的号码是:"+index++);
}
}
第二种:同步代码块
public class SyncClass implements Runnable{
private Object MUTEX=new Object();
private int index=1;
@Override
public void run() {
synchronized (MUTEX){
System.out.println(Thread.currentThread()+"的号码是:"+index++);
}
}
}
public class SyncClass implements Runnable{
private int index=1;
@Override
public void run() {
synchronized (this){
System.out.println(Thread.currentThread()+"的号码是:"+index++);
}
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SyncClass runnable=new SyncClass();
Thread thread1=new Thread(runnable,"一号");
Thread thread2=new Thread(runnable,"二号");
Thread thread3=new Thread(runnable,"三号");
Thread thread4=new Thread(runnable,"四号");
Thread thread5=new Thread(runnable,"五号");
Thread thread6=new Thread(runnable,"六号");
Thread thread7=new Thread(runnable,"七号");
Thread thread8=new Thread(runnable,"八号");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
thread6.start();
thread7.start();
thread8.start();
}
}
打印结果如下:
12-20 15:48:10.617 3914-3938/e.lenovo.textapplication I/System.out: Thread[六号,5,main]的号码是:1
12-20 15:48:10.617 3914-3939/e.lenovo.textapplication I/System.out: Thread[七号,5,main]的号码是:2
12-20 15:48:10.618 3914-3937/e.lenovo.textapplication I/System.out: Thread[五号,5,main]的号码是:3
12-20 15:48:10.618 3914-3936/e.lenovo.textapplication I/System.out: Thread[四号,5,main]的号码是:4
12-20 15:48:10.618 3914-3935/e.lenovo.textapplication I/System.out: Thread[三号,5,main]的号码是:5
12-20 15:48:10.620 3914-3934/e.lenovo.textapplication I/System.out: Thread[二号,5,main]的号码是:6
12-20 15:48:10.620 3914-3933/e.lenovo.textapplication I/System.out: Thread[一号,5,main]的号码是:7
12-20 15:48:10.621 3914-3940/e.lenovo.textapplication I/System.out: Thread[八号,5,main]的号码是:8
网友评论