Thread pool

Thread the super a: blog.csdn.net/cuigx1991/a…


The thread pool: www.importnew.com/19011.html

www.jianshu.com/p/098819be0…


ExecutorService

Blog.csdn.net/yuzhiboyi/a…


Callable and Runnable

Blog.csdn.net/lu123535884…

Callable returns results, but runnable does not.


The code:

public  class TestCallable implements Callable<String>{

    @Override
    public String call() throws Exception {
        Thread.sleep(3000);
        return "Hello World"; }}Copy the code

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TestCallable testCallable = new TestCallable();
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    Future<String> future = executorService.submit(testCallable);
    try {
        System.out.println(future.get());
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    System.out.println("11111111111111");
}Copy the code

The TestCallable thread will block the main thread because future.get() will block the current thread. Until the call method of callable ends.


CountDownLatch

You can block the current thread, wait for another thread to finish executing the results and then return the results synchronously, asynchronously to synchronization.

Note the conversion from asynchronous to synchronous

1) Asynchronous data must be in the child thread, otherwise it will cause the current thread to stall.

2) If you need to synchronize data from the main thread, but the child thread is fetching data, the child thread should not use new Handler(looper.getMainLooper ()) to delay operations, otherwise the child thread will not be able to reduce the countDownLatch, and the main thread will end up waiting.


Using Handler in child threads:

HandlerThread handlerThread = new HandlerThread("The pure 24 protocol is used to analyze the received data.") {}; handlerThread.start(); mHandler = new Handler(handlerThread.getLooper());Copy the code

3) Await method after another thread is opened, otherwise other thread will block the current thread before it is opened.


Second, thread interaction

1. Wake up and wait (Wait and notify)

Related blogs: blog.csdn.net/qq_26504875…

Common exception: http://blog.csdn.net/zhouxiaoyun0228/article/details/7757313

Note: 1) Wake up and wait have strict usage conditions, object listeners can only be called in the listening thread.

2) Wait and notify can only be called in synchronized code blocks

3) When a task synchronization method is completed, the listener is called to wait for the current thread.

4) Wait and notify are methods of object, but they act as locks to control threads.

5) Wait and notify are more suitable for two or more threads working together


Example code:

Two interactive thread classes:

public class MyThread1 extends Thread{
    private Object lock;
    private int index = 0;

    public MyThread1(Object lock){
        this.lock = lock;
    }
    @Override
    public void run(){
        synchronized (lock) {
            while (true){
                System.out.println("MyThread1 "+System.currentTimeMillis());
                index++;
                if(index == 10){
                    lock.notify();
                    break;
                }
                if(index % 5 == 0){
                    try {
                        lock.notify();
                        System.out.println("MyThread1 wait");
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

    }
}Copy the code

public class MyThread2 extends Thread{
    private Object lock;
    private int index = 0;

    public MyThread2(Object lock){
        this.lock = lock;
    }
    @Override
    public void run(){
        synchronized (lock) {
            while (true){
                System.out.println("MyThread2 "+System.currentTimeMillis());
                index++;
                if(index == 10){
                    lock.notify();
                    break;
                }
                if(index % 5 == 0){
                    try {
                        lock.notify();
                        System.out.println("MyThread2 wait");
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}Copy the code


Task call class for 2 interactive threads:

public class Thread1Tasker implements ITask{
    private Object lock;
    private final static Thread1Tasker instance = new Thread1Tasker();
    public final static Thread1Tasker getInstance() {return instance;
    }

    public Thread1Tasker setLock(Object lock) {
        this.lock = lock;
        return this;
    }

    @Override
    public void start() { MyThread1 t1 = new MyThread1(lock); t1.start(); }}Copy the code


public class Thread2Tasker implements  ITask{
    private Object lock;

    private final static Thread2Tasker instance = new Thread2Tasker();
    public final static Thread2Tasker getInstance() {return instance;
    }

    public Thread2Tasker setLock(Object lock) {
        this.lock = lock;
        return this;
    }


    @Override
    public void start() { MyThread2 t2 = new MyThread2(lock); t2.start(); }}Copy the code

The main method calls the task:

public class Test3 { public static void main(String[] args) throws InterruptedException { Object lock = new Object(); Thread1Tasker.getInstance().setLock(lock) .start(); Thread2Tasker.getInstance().setLock(lock) .start(); }}Copy the code

Result printout:

MyThread1 1516939281372

MyThread1 1516939281372

MyThread1 1516939281372

MyThread1 1516939281372

MyThread1 1516939281372

MyThread1 wait

MyThread2 1516939281374

MyThread2 1516939281374

MyThread2 1516939281374

MyThread2 1516939281374

MyThread2 1516939281374

MyThread2 wait

MyThread1 1516939281374

MyThread1 1516939281374

MyThread1 1516939281374

MyThread1 1516939281374

MyThread1 1516939281374

MyThread2 1516939281374

MyThread2 1516939281374

MyThread2 1516939281374

MyThread2 1516939281374

MyThread2 1516939281374

You can see that two threaded tasks are executed alternately


Third, HandlerThread

www.cnblogs.com/coding-way/…

InputStream is blocked

www.cnblogs.com/MyFavorite/…

Five,Java concurrent programming: Volatile keyword resolution

www.cnblogs.com/dolphin0520…

The meaning of the volatile keyword in Java

www.cnblogs.com/aigongsi/ar…



Blog.csdn.net/javazejian/…

The last

Like you can pay attention to my public number, Java small melon brother sharing platform. There are a lot of technical documents and interview documents that I usually arrange in it