线程同步机制
- 在多线程编程,一些敏感数据不允许被多个线程同时访问,此时就使用同步访问技术,保证数据在任何时刻,最多有一个线程访问,以保证数据的完整性。
- 也可以这里理解:线程同步,即当有一个线程在对内存进行操作时,其他线程都不可以对这个内存地址进行操作,直到该线程完成操作,其他线程才能对该内存地址进行操作。
互斥锁
- Java语言中,引入了对象互斥锁的概念,来保证共享数据操作的完整性。
- 每个对象都对应于一个可称为“互斥锁”的标记,这个标记用来保证在任一时刻,只能有一个线程访问该对象。
- 关键字 synchronized 来与对象的互斥锁联系。当某个对象用synchronized修饰时,表明该对象在任一时刻只能由一个线程访问
- 同步的局限性:导致程序的执行效率要降低
- 同步方法((非静态的)的锁可以是this,也可以是其他对象(要求是同一个对象);同步方法(静态的)的锁为当前类本身。
注意事项和细节
- 同步方法如果没有使用static修饰:默认锁对象为 this
- 如果方法使用static修饰,默认锁对象:当前类.class
- 实现的落地步骤:
需要先分析上锁的代码,选择同步代码块或同步方法,要求多个线程的锁对象为同一个即可!
同步具体方法—synchronized
1、同步代码块
synchronized(对象) { //得到对象的锁,才能操作同步代码
//需要被同步代码;
}
2、synchronized 还可以放在方法声明中,表示整个方法—为同步方法
public synchronized void m (String name){
//需要被同步的代码
}
使用互斥锁—同步方法解决售票问题
/**
* 使用多线程,模拟三个窗口同时售票 100张
*/
public class SellTicket {
public static void main(String[] args) {
SellTicket03 sellTicket03 = new SellTicket03();
new Thread(sellTicket03).start();//第一个线程
new Thread(sellTicket03).start();//第二个线程
new Thread(sellTicket03).start();//第三个线程
}
}
//实现接口,使用synchronized实现线程同步
class SellTicket03 implements Runnable{
private int ticketNum = 100;
private boolean loop =true;
public synchronized void sell() {//同步方法,在同一时刻,只能有一个线程来执行run方法
if (ticketNum <= 0)
{
System.out.println("售票结束");
loop=false;
return;
}
//休眠50毫秒
try {
Thread.sleep(50);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("窗口 "+ Thread.currentThread().getName()+" 售出一张票"+
" 剩余票数= "+(--ticketNum));
}
@Override
public void run()
{
while (loop)
{
sell();//sell方法是一个同步方法
}
}
}
使用互斥锁—同步代码块锁解决售票问题
/**
* 使用多线程,模拟三个窗口同时售票 100张
*/
public class SellTicket {
public static void main(String[] args) {
SellTicket03 sellTicket03 = new SellTicket03();
new Thread(sellTicket03).start();//第一个线程
new Thread(sellTicket03).start();//第二个线程
new Thread(sellTicket03).start();//第三个线程
}
}
//实现接口,使用synchronized实现线程同步
class SellTicket03 implements Runnable{
private int ticketNum = 100;
private boolean loop =true;
//1、public synchronized void sell()好就是一个同步方法,这时锁在this对象
//2、也可以在代码块上写synchronize ,同步代码块,互斥锁还是在this对象
public void sell() {
synchronized (this){
if (ticketNum <= 0)
{
System.out.println("售票结束");
loop=false;
return;
}
//休眠50毫秒
try {
Thread.sleep(50);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("窗口 "+ Thread.currentThread().getName()+" 售出一张票"+
" 剩余票数= "+(--ticketNum));
}}
@Override
public void run()
{
while (loop)
{
sell();//sell方法是一个同步方法
}
}
}
静态同步方法的锁
class SellTicket03 implements Runnable{
//1、静态方法:public synchronized static void m1() {},锁是加在SellTicket03.class
//2、如果在静态方法中,实现一个同步代码块。
/*
synchronized (SellTicket03.class) {
System.out.println("m2");
}
*/
public synchronized static void m1(){
}
public static void m2() {
synchronized (SellTicket03.class) {
System.out.println("m2");
}
}
}