Java - thread pool Basics

1, the basic concept

1, shared resources

Multiple threads to access (read or write) a copy of the same resource, the resource is known as a shared resource. How to ensure that multiple threads access to the data is the same, is called data synchronization or resource synchronization.

2, thread communication

Inter-thread communication, also known as internal process communication, and network communication process different communication; multiple threads to achieve mutually exclusive access to resources of time, it sends a signal to each other.

2, synchronous, asynchronous, blocking, non-blocking

Synchronous and asynchronous way is to get the result, blocking and non-blocking is whether to wait for the results to complete other things.

Synchronous blocking (BIO), to wait for the client's data has been read, also need blocking client determines whether there is data.

Synchronous non-blocking (NIO), you need to wait for the client's data has been read, but by way of polling data to determine whether the client can do other things.

Asynchronous blocks, waiting for the results of a callback notification, cpu's in a dormant waiting.

Asynchronous non-blocking (AIO), the operating system to complete the read operation, the read completion notification callback, use the thread pool way to poll the client data, you can do other things.

Concurrent, single cpu can handle multiple tasks, but only one task at the same time run.

Parallel multiple tasks to run on multiple cpu, the same real time operation.

2, the life cycle

//当new一个Thread的时候,此时只是一个简单的java对象
NEW

//调用start方法之后,进入该状态,此时只是处于可执行状态,但还未执行
RUNNABLE

//处于执行状态,可由于调用sleep/join和wait、阻塞IO操作、尝试获取锁,进入 BLOCKED 状态
//可由于cpu调度、调用yield,进入 RUNNABLE 状态
RUNNING   

//在sleep完毕和wait唤醒、阻塞IO操作完成、获得了锁、阻塞过程被interrupt,进入 RUNNABLE 状态
BLOCKED 

3, daemon thread

General use new Thread created thread are non-daemon thread, also known as user threads. To guard the way is that, before the run, call setDaemon (true). Daemon thread, just to serve user threads, so once all the user threads have finished running, the guardian would be the end. On the contrary, as long as there exists a non-daemon thread, then the guard would not terminate the thread.

Daemon threads scenarios: garbage collection, heartbeat detection, spelling check thread

package com.vim;

import java.util.concurrent.TimeUnit;

public class App {
    public static void main( String[] args ) throws Exception{
        Thread t = new Thread(()->{
            while (true){
                try {
                    TimeUnit.SECONDS.sleep(1);
                    System.out.println("......");
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        //只有t设置了此处,才会随着父进程的退出而退出
        t.setDaemon(true);
        t.start();
        TimeUnit.SECONDS.sleep(5);
        System.out.println("main is over!");
    }
}

4, a thread yield, sleep

After the yield, called threads concessions into RUNNABLE state from RUNNING state, it is possible to switch again to grab executive power, into the RUNNING state.

sleep, can block the thread entered the BLOCKED state, and this was suspended, so that the cpu; only the blocking time is up, will enter RUNNABLE state, not necessarily immediately acquire the right to perform the cpu.

The role of sleep (0) is triggered once the operating system immediately re-CPU competition, perhaps the result of competition still get current thread CPU control, may be replaced by another thread gets control of the CPU.

package com.vim;

public class App {
    public static void main( String[] args ) throws Exception {
        new Thread(()->{
            try {
                while (true){
                    Thread.sleep(0);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }).start();
    }
}

5, thread interrupt

wait, sleep, join the current thread into the blocked state, and interrupt can be interrupted blocked, but is merely intended to present traffic congestion state. InterruptException current thread will throw an exception as a signal notification. This notification will interrupt flag is set to true, but interrupted for a blocking state of the status bit is reset to false. Judged by thread.isInterrupted (), of course, in the blocking state, it will be removed, thus affecting the results of the method.

package com.sample.modules.test;

import java.util.concurrent.TimeUnit;

public class Test {

    //中断一个线程,中断位 true
    public static void test1() throws Exception{
        Thread t = new Thread(()->{
            //2.获取当前的 interrupt flag 状态为 true
            System.out.println(Thread.currentThread().isInterrupted());
        });
        t.start();

        //1.中断线程
        t.interrupt();
        TimeUnit.MINUTES.sleep(4);
    }

    //中断一个线程,中断位 false
    public static void test2() throws Exception{
        Thread t = new Thread(()->{
            //2.清除中断位
            Thread.interrupted();
            //3.获取当前的 interrupt flag 状态为 false
            System.out.println(Thread.currentThread().isInterrupted());
        });
        t.start();

        //1.中断线程
        t.interrupt();
        TimeUnit.MINUTES.sleep(4);
    }

    //中断一个线程,中断位 false
    public static void test3() throws Exception{
        Thread t = new Thread(()->{
            //2.中断wait、sleep、join导致的阻塞
            try {
                TimeUnit.SECONDS.sleep(5);
            }catch (InterruptedException e){
                System.out.println("i am interrupted");
            }
            //3.获取当前的 interrupt flag 状态为 false
            System.out.println(Thread.currentThread().isInterrupted());
        });
        t.start();

        //1.中断线程
        t.interrupt();
        TimeUnit.MINUTES.sleep(4);
    }

    //阻塞之前中断结果:false、true、i am interrupted、false
    public static void test4(){
        Thread.interrupted();
        System.out.println("interrupt flag: "+Thread.currentThread().isInterrupted());
        Thread.currentThread().interrupt();
        System.out.println("interrupt flag: "+Thread.currentThread().isInterrupted());
        try {
            TimeUnit.SECONDS.sleep(1);
        }catch (InterruptedException e){
            System.out.println("i am interrupted");
        }
        System.out.println("interrupt flag: "+Thread.currentThread().isInterrupted());
    }

    public static void main(String[] args) throws Exception{
        test3();
    }
}

6, the thread join

parent thread calls child thread join method, actually calls join (0), which added a lock, the thread loop to determine child survival status, of course, each call to wait (0) method cycle, so you can make other threads can also enter join (0) method.

//当前方法没有上锁
public final void join() throws InterruptedException {
    join(0);
}

//此方法上锁,此时其他线程可以进入 join(),但不可以进入 join(0)
//不断的检查线程是否 alive,调用 wait(0),这样就释放了锁,其他的线程就可以进入 join(0),也就是可以有多个线程等待某个线程执行完毕
//一旦线程不在 alive,那么就会返回到 join() 方法,调用的线程就可以继续执行下去
public final synchronized void join(long millis){
    if (millis == 0) {
         while (isAlive()) {
            wait(0);
        }
    }
}

7, thread notifies notify, wait

These two methods, derived from the Object class, with the use of both. wait method belongs to object methods, you must obtain before calling monitor lock of the object, after the call, it will release the monitor lock of the object to enter the object associated waitset and wait for other threads using notify wake.

A typical production and consumption scenarios:

Producers in the production of goods, the warehouse (Isochronous Resource) were locked, if the current warehouse is not full, then add products to use notifyAll notify the consumer; if the current warehouse is full, use the wait release the lock, enter waitset blocked notifyAll wait for notification.

Consumers, consumption came to the warehouse, the warehouse (synchronous resources) to lock if the current warehouse products, then take the product, use notifyAll notify the producer; if the current warehouse is empty, use the wait release the lock, enter waitset blocking wait notifyAll notice.

When notifyAll comes, for all producers and consumers, the opportunity to have a key to get the warehouse, the competition will go into more decision logic again.

8 difference, wait and sleep in

In common:

The thread into the blocked state; interrupt can be interrupted;

the difference:

There is a wait Object, sleep is a unique Thread.

wait process must run in synchronization, sleep required.

wait will release the lock, if sleep on the synchronization method, and will not release the lock.

9, exception handling thread

package com.sample.modules.test;

public class Test {

    public static void main(String[] args) throws Exception{
        Thread t = new Thread(()->{
            int i = 1/0;
        });
        t.setUncaughtExceptionHandler((thread, e)->{
            System.out.println("exception...");
        });
        t.start();
    }
}

10, computer memory model and the Java Memory Model

Principle retrospective: cpu in the instruction execution time, data from the main memory (RAM), since both the speed and the like are not serious, occurred between the cache buffer; generally divided into L1, L2, L3 cache per CPU core comprising set of L1, L2 and L3 cache shared.

Cache coherency problem: when a plurality of processors of a computing task referring to the same main memory area, each cpu variables removed from the main memory, into the local cache, then calculated, written into the cache, then the cache flushed to main memory.

  • I read the main memory into the cache
  • I ++ to be
  • The write-back cache results
  • Refresh the cache back to main memory.

Cache coherency protocol: cpu operation data in the cache, if a shared variable is found, then at the time of writing, it will signal the other of the variable cpu cache line is invalidated, performing other cpu when the variable read, you need to go to the main memory read.

Compared computer memory model, Java memory model: thread == CPU, working memory == CPU cache, main memory == main memory.

12, the three major characteristics of concurrent programming

  • Atomicity, multiple operation, either all be executed or all not be executed.
  • Visibility, a thread of shared variables, has been modified, then other threads can see the value immediately after the modification.
  • Orderliness, the program code during execution of the order.

13, synchronized keyword

synchronized keyword provides a mechanism to lock, to ensure mutually exclusive access to shared variables, namely the same time, only one thread synchronized access to resources.

Terms of memory, monitor enter and monitor exit two JVM command to ensure that any thread must get data from main memory before the monitor enter, after the monitor exit, you must refresh the updated value to the main memory. Both JVM command, strict compliance happends-before principle, there must exist before a monitor enter instruction that is a monitor exit command.

The keyword for exclusive access to a synchronized resource, very effective, but the other did not get to monitor the thread, in the end how long blocking, unblocking can not advance, these are unknown. To this end, java provides other solutions to explicitly lock for us. As ReentrantLock.

Guess you like

Origin blog.csdn.net/sky_eyeland/article/details/93177820