Java - 由面向对象看多线程

多线程核心的两个对象

Lock lock;    // any Object can be a Lock
Thread thread;    // thread just a thread
抢锁/释放锁
/* 
    !! FAKE CODE
*/

Object specificLock = new Object();

int initialSize = 1_000_000;

List threadList = new ArrayList<>();
for (int i = 0; i < initialSize ; i++) {
    threadList.add(new Thread());
}

// ????, pity, Thread.class don't have a method called rob();
robSuccessThread = threadList[ 0 ... 999_999 ].robAtTheSameTime(specificLock);     

doSomething();

robSuccessThread.release(specificLock );
  • 线程操作系统最基础的调度单元
  • 线程对锁的获取及释放操作系统完全掌控, 用户无权控制线程对锁的抢占/释放成功与否
  • JVM系统线程进行封装, 提供synchronized关键字
Object lock = new Object();

synchronized (lock) {    
    // moniter-enter, 抢lock成功, 才会进入此区块, 抢lock失败, 则进入等锁队列;
    doSomething();
} // moniter-exit, 释放lock

synchronized的语义: 多条线程同时执行到此对象实例的方法时, 仅有抢锁成功的线程能够进入区块执行; 其余抢锁失败的线程, 则进入到等锁队列

  • 拆解一下, syn关键字, 其实涉及到5个对象: 线程|对象实例|方法|锁|等锁队列;

你可能感兴趣的:(多线程,java)