网站建设合同封面模板下载,蓝色大气企业网站,wordpress词典插件下载,网站开发员工结构线程同步机制
在多线程编程#xff0c;一些敏感数据不允许被多个线程同时访问#xff0c;此时就使用同步访问技术#xff0c;保证数据在任何时刻#xff0c;最多有一个线程访问#xff0c;以保证数据的完整性。也可以这里理解:线程同步#xff0c;即当有一个线程在对内存… 线程同步机制
在多线程编程一些敏感数据不允许被多个线程同时访问此时就使用同步访问技术保证数据在任何时刻最多有一个线程访问以保证数据的完整性。也可以这里理解:线程同步即当有一个线程在对内存进行操作时其他线程都不可以对这个内存地址进行操作,直到该线程完成操作其他线程才能对该内存地址进行操作。
互斥锁
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(售票结束);loopfalse;return;}//休眠50毫秒try {Thread.sleep(50);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println(窗口 Thread.currentThread().getName() 售出一张票 剩余票数 (--ticketNum));}Overridepublic 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(售票结束);loopfalse;return;}//休眠50毫秒try {Thread.sleep(50);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println(窗口 Thread.currentThread().getName() 售出一张票 剩余票数 (--ticketNum));}}Overridepublic 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);}}
}