14-synchronized保证线程安全的原理(理论层面)
在看synchronized之前,我们首先来看内置锁,什么是内置锁呢?就是说,Java中每一个对象都可以用作同步的锁,那么,这些锁就被称之为内置锁.
其实synchronized的原理其实就是加了锁,内置锁和互斥锁所决定的。每个对象都有锁,而这些锁都是互斥的,一个进来之后,另外的就不能进来了,因此就可以保证线程的安全性。
daim 代码示范:
package com.roocon.thread.t3; public class Sequence { private int value; /** * synchronized 放在普通方法上,内置锁就是当前类的实例 * @return */ public synchronized int getNext() { return value ++; } /** * 修饰静态方法,内置锁是当前的Class字节码对象 * Sequence.class * @return */ public static synchronized int getPrevious() { // return value --; return 0; } public int xx () { // monitorenter synchronized (Sequence.class) { if(value > 0) { return value; } else { return -1; } } // monitorexit } public static void main(String[] args) { Sequence s = new Sequence(); // while(true) { // System.out.println(s.getNext()); // } new Thread(new Runnable() { @Override public void run() { while(true) { System.out.println(Thread.currentThread().getName() + " " + s.getNext()); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { while(true) { System.out.println(Thread.currentThread().getName() + " " + s.getNext()); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { while(true) { System.out.println(Thread.currentThread().getName() + " " + s.getNext()); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } }
上一篇:
通过多线程提高代码的执行效率例子
下一篇:
【Pandas学习】读、存excel数据