美文网首页
Java Thread Overview

Java Thread Overview

作者: 超越爱迪生 | 来源:发表于2016-04-17 23:00 被阅读87次

    线程的创建#

    创建线程有两种方式:继承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);
        }
    }
    

    线程池#

    相关文章

      网友评论

          本文标题:Java Thread Overview

          本文链接:https://www.haomeiwen.com/subject/sdkolttx.html