Java Thread Overview

线程的创建#

创建线程有两种方式:继承Thread类,或者实现Runnable接口

继承Thread类##

public class MyThread extends Thread{
    public void run(){
        System.out.println("MyThread running");
    }
}

MyThread myThread = new MyThread();
myThread.start();

也可以创建一个匿名类继承自Thread

Thread thread = new Thread(){
    public void run(){
        System.out.println("Thread running");
    }
}

thread.start();

实现Runnable接口##

public class MyRunnable implements Runnable{
    public void run(){
        System.out.println("MyRunnable running");
    }
}

Thread myThread = new Thread(new MyRunnable());
myThread.start();

常见错误:start()而不是run()##

不管实现Runnable接口还是继承自Thread类,通过start方法去启动该线程。如果调用的是run方法,其实是在当前线程执行的。
这可以通过下面的例子验证


public class MyThread extends Thread{

    public void run(){
        System.out.println(Thread.currentThread() + ": running 1");
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread() + ": running 2");
    }
    
    public static void main(String[] args) throws InterruptedException {
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();
        thread1.run();
        thread2.run();
        thread1.join();
        thread2.join();
    }
}

输出结果是

Thread[main,5,main]: running 1
Thread[main,5,main]: running 2
Thread[main,5,main]: running 1
Thread[main,5,main]: running 2

而如果把run改为start,输出结果才符合我们的预期

Thread[Thread-0,5,main]: running 1
Thread[Thread-1,5,main]: running 1
Thread[Thread-0,5,main]: running 2
Thread[Thread-1,5,main]: running 2

线程安全#

下图描述了java内存模型


java-memory-model.png

多线程之间可能会共享变量。当他们同时修改一个共享变量时,就会产生race condition。这时候,可以使用synchronized关键字或者Lock避免race condition。

synchronized##

a synchronized block guarantees that only one thread can enter a given critial section. synchronized block also guarantee that all the variables accessed inside the synchronized block will be read in from main memory, and when the thread exists synchronized block, all update variables will be flushed back to main memory again.

synchronized关键字可以用来标记四中不同的block。

  • instance method
  • static method
  • code blocks inside instance method
  • code blocks inside static method
  public class MyClass {
  
    public synchronized void log1(String msg1, String msg2){
       log.writeln(msg1);
       log.writeln(msg2);
    }

  
    public void log2(String msg1, String msg2){
       synchronized(this){
          log.writeln(msg1);
          log.writeln(msg2);
       }
    }
  }

Lock##

Lock其实是用synchronized关键字实现的。下面是一个简单的实现

public class Lock{
    private boolean isLocked = false;

    public synchronized void lock()
        throws InterruptedException{
        while(isLocked){
          wait();
        }
        isLocked = true;
    }

    public synchronized void unlock(){
        isLocked = false;
        notify();
    }
}

java.util.concurrent.Lock包中,Lock是一个接口,有以下几个方法

  • lock()
  • lockInterruptibly()
  • trylock()
  • trylock(long timeout, TimeUnit timeUnit)
  • unlock()

实现Lock接口的类有ReentrantLock和ReadWriteLock。
ReentrantLock就是普通的lock。
ReadWriteLock实现了多读,单写。

ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

readWriteLock.readLock().lock();
// multiple readers can enter this section
// if not locked for writing, and not writers waiting
// to lock for writing.
readWriteLock.readLock().unlock();

readWriteLock.writeLock().lock();
// only one writer can enter this section,
// and only if no threads are currently reading.
readWriteLock.writeLock().unlock()

synchronized和Lock##

synchronized和Lock还是有些区别的:

  • 如果有多个线程等待,synchronized block不保证这些线程进入的顺序就是他们到达等待的顺序
  • 因为不能传递参数给synchronized block,因此没法设置timeout时间
  • synchronized block必须在一个函数体内。但是lock和unlock可以在不同的函数体内。

线程安全的容器##

java.util.concurrent包里面提供了很多线程安全的容器,可以让我们在多线程编程的时候更加容易。

  • BlockingQueue
  • ArrayBlockingQueue
  • LinkedBlockingQueue
  • DelayQueue
  • PriorityBlockingQueue
  • SynchronousQueue
  • BlockingDeque
  • LinkedBlockingDeque
  • ConcurrentMap
  • ConcurrentNavigableMap

线程安全的类##

多线程使得任何操作都变得如履薄冰。比如,你想对一个int类型的共享变量进行++操作,那么传统的 i++不是线程安全的。因为这句并不是原子操作。因为java给我们提供了一些原子操作类。

  • AtomicBoolean
  • AtomicInteger
  • AtomicLong
  • AtomicReference
  • AtomicStampedReference
  • AtomicIntegerArray
  • AtomicLongArray
  • AtomicReferenceArray

线程同步#

wait & notify##

java.lang.Object定义了三个方法 wait(), notify(), notifyAll()。通过这几个方法,可以让一个线程等待一个信号,也可以让另外一个线程发送一个信号。调用了wait()的线程会贬称inactive状态,直到另外一个线程调用notify()。
需要注意的是,调用wait或者notify的线程必须要获得这个对象的锁。也就是说,一个线程必须在synchronized block中调用wait notify。

public class MonitorObject{
}

public class MyWaitNotify{
  MonitorObject myMonitorObject = new MonitorObject();

  public void doWait(){
    synchronized(myMonitorObject){
      try{
        myMonitorObject.wait();
      } catch(InterruptedException e){...}
    }
  }

  public void doNotify(){
    synchronized(myMonitorObject){
      myMonitorObject.notify();
    }
  }
}

Wouldn't the waiting thread keep the lock on the monitor object (myMonitorObject) as long as it is executing inside a synchronized block? Will the waiting thread not block the notifying thread from ever entering the synchronized block in doNotify()? The answer is no. Once a thread calls wait() it releases the lock it holds on the monitor object. This allows other threads to call wait() or notify() too, since these methods must be called from inside a synchronized block.
Once a thread is awakened it cannot exit the wait() call until the thread calling notify() has left its synchronized block. In other words: The awakened thread must reobtain the lock on the monitor object before it can exit the wait() call, because the wait call is nested inside a synchronized block. If multiple threads are awakened using notifyAll() only one awakened thread at a time can exit the wait() method, since each thread must obtain the lock on the monitor object in turn before exiting wait().

semaphore##

semaphore实现的功能就类似厕所有5个坑,假如有10个人要上厕所,那么同时只能有多少个人去上厕所呢?同时只能有5个人能够占用,当5个人中 的任何一个人让开后,其中等待的另外5个人中又有一个人可以占用了。

Semaphore semaphore = new Semaphore(5);

//critical section
semaphore.acquire();
...
semaphore.release();

除了acquire和release,Semaphor还提供了其他接口:

  • availablePermits()
  • acquireUninterruptibly()
  • drainPermits()
  • hasQueuedThreads()
  • getQueuedThreads()
  • tryAcquire()

CountDownLatch##

CyclicBarrier##

CyclicBarrier要做的事情是让一组线程到达一个屏障时被阻塞,直到最后一个线程到达屏障时,屏障门才会打开。

public class CyclicBarrierTest {

    static CyclicBarrier c = new CyclicBarrier(2);

    public static void main(String[] args) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    c.await();
                } catch (Exception e) {

                }
                System.out.println(1);
            }
        }).start();

        try {
            c.await();
        } catch (Exception e) {

        }
        System.out.println(2);
    }
}

线程池#

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,688评论 1 330
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,559评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,749评论 0 226
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,581评论 0 191
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,741评论 3 271
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,684评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,122评论 2 292
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,847评论 0 182
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,441评论 0 228
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,939评论 2 232
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,333评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,783评论 2 236
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,275评论 3 220
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,830评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,444评论 0 180
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,553评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,618评论 2 249

推荐阅读更多精彩内容