Concurrent Programming Study Notes (a) - initial concurrent programming

Disclaimer: This article is a blogger original, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/weixin_36904568/article/details/90339246

A: Concurrent Programming

1. Basic Concepts

(1) Synchronous and asynchronous

  • Sync: synchronization method Once called, the caller must wait for the behavior of the method call returns to continue behind
  • Asynchronous: Asynchronous method in another thread execution method call returns immediately, the caller can continue to operate behind, inform the caller after the operation is completed, the result is returned

(2) concurrently with the parallel

  • Concurrently (a CPU): alternately a plurality of tasks (perhaps serial)
  • Parallel (multiple CPU): multiple tasks simultaneously

(3) critical section

It represents a public resource that can be used by multiple threads. The same time only one thread to use.

(4) blocking and non-blocking

  • Blocked: Thread waiting for a critical section resources, is suspended
  • Non-blocking: All threads will try to go on

(5) Deadlock and livelock

  • Deadlock: other resources between threads possession of each other's needs, but not released, but also to ask for each other's resources, resulting in multiple threads can not wait for a complete resource
  • Livelock: other resources between threads possession of each other's needs, wants release, and to ask for each other's resources, resulting in multiple threads can not wait for a complete resource
  • Hunger: Thread some reason can not get resources, it has been unable to lead the implementation of

2. concurrency level

(1) blocking (Pessimistic strategy)

Before the other thread to release resources to the current thread can not proceed

(2) without hunger

  • For non-equity Lock: system allows high-priority thread to perform, leading to a low priority thread starvation
  • For fair lock: In accordance with the principle of first come, first served, all threads have the opportunity to perform

(3) Accessible (optimistic strategy)

Think no conflict between threads, multiple threads can be no barriers to enter the critical section. If it detects abnormal data is rolled back their operations, ensure data security (no thread could lead to leave the critical section)

Conformity mark
  1. Thread before the operation, read and save the mark
  2. If you need to change the critical zone data, you need to update the tag tell other threads unsafe
  3. After the operation is completed, read again, whether the check mark is changed. If the agreement is proof there is no conflict, and if not then prove that there is a conflict needs to be retried

(4) no lock

Barrier-free basis, there must be a requirement thread can leave the critical region for a limited time (may lead to retry threads appear hungry)

(5) without waiting

On the basis of no lock on, we require that all threads are able to leave the critical region for a limited time

RCU
  • Read: not controlled
  • Writes: by modifying the copy of the data, write-back data at the right time

3. Concurrent's Law

(1) Amdahl's Law

In order to increase system speed, it is necessary to increase the processor CPU, while improving the system modules proportion parallelizable

(2) Gustafson Law

If serialization small proportion, a large proportion of parallelization, the processor CPU can be increased to improve the speed of the system

4. Java memory model JMM

(1) Atomic

A operation is not interrupted, will not be disturbed by other threads.
(For 32-bit virtual machine, if the 64-bit data operation, it is not atomic)

(2) visibility

When a thread changes the value of a shared variable, other threads immediately know that this modification
(cache optimization, hardware optimization, instruction reordering, compiler optimization may cause the operation is not visible)

(3) ordering

Execution order

Instruction reordering

Can ensure the consistency of serial semantics, but can not guarantee semantic consistency multithreaded
number of interruption in the pipeline can be reduced

Happen-Before Principles

  • Principles program sequence (within a single thread)
  • volatile principles (written prior to reading)
  • Lock principle (unlocked prior to the subsequent lock)
  • Transitive
  • Thread start () prior to its every movement
  • Every movement thread prior to its end
  • Thread interrupt interrupt () prior to the interrupted thread code
  • The constructor of the object prior to its finalize ()

Two: Java concurrent design

1. Thread life cycle

  • New New: created, has not started
  • Run Runable: Ready or performing
  • Wait indefinitely Waiting: waiting to be awakened by other threads
  • Deadline waiting Timed Waiting: automatic wake-up after a period of time
  • Blocked Blocked: waiting to acquire an exclusive lock
  • End Terminated: end of the thread execution

2. Thread the basic operation

(1) New

Do not use thread.run () method to open a thread, it will only serial execution run () method.
Should use thread.start (); method New Thread

Created by inheritance:
public class MyThread{
    static class Thread1 extends Thread {
        @Override
        public void run() {
            System.out.println("通过继承的方法创建线程");
        }
    }

    public static void main(String[] args) {
        Thread1 thread1 = new Thread1();
        thread1.start();
       
    }
}

Created by an anonymous inner class:
    public static void main(String[] args) {
        Thread thread = new Thread(){
            @Override
            public void run() {
                System.out.println("通过匿名内部类的方法创建线程");
            }
        };
        thread.start();
    }
By implementing the interface to create:
public class MyThread{

    static class Thread2 implements Runnable{

        @Override
        public void run() {
            System.out.println("通过接口的方法创建线程");
        }
    }

    public static void main(String[] args) {
        Thread thread = new Thread(new Thread2());
        thread.start();
    }
}

(2) Sleep

By Thread.sleep (time), thread to sleep for some time, if interrupted hibernation will throw InterruptedException

Sleep still hold resources can not be awakened by other threads!

(3) termination

Instead of using thread.stop () method, it will direct the end of the thread, resulting in inconsistent data.
Need to decide when to end the thread (state amount)

public class MyThread {

    static class Thread1 extends Thread {

	//标志结束的信号
        private boolean stop;

        public void stopMe() {
            stop = true;
        }

        @Override
        public void run() {
            while (true) {
                System.out.println("实现线程");
                try {
                	//让线程慢一点,容易观察
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //接收到结束信号,停止循环
                if (stop) {
                    System.out.println("结束了");
                    break;
                }
            }
        }

    }

    public static void main(String[] args) throws InterruptedException {
        Thread1 thread = new Thread1();
        thread.start();
//        thread.stop();
	//等待1秒后,让线程停止
        Thread.sleep(1000);
        thread.stopMe();
    }
}

(4) interrupts

Tell the system should quit, determined by the system

  • Set the interrupt flag: thread.interrupt (); (similar thread.stopMe ();)

  • Check the interrupt flag: Thread.currentThread () isInterrupted (); (similar to the judge sentences if (stop)).

  • Check the interrupt flag bit and clear: Thread.interrupted ();

Special:

Interrupt method is not only the end of the reminder system, can handle special cases of sleep or wait

public class MyThread {

    static class Thread1 extends Thread {

        private boolean stop;

        public void stopMe() {
            stop = true;
        }

        @Override
        public void run() {
            while (true) {
                System.out.println("实现线程");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                	//抛出异常的同时会清除中断标记
                    System.out.println("我在睡觉你还中断我?");
                    //再次设置标记
                    Thread.currentThread().interrupt();
                }
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("结束了");
                    break;
                }
            }
        }

    }

    public static void main(String[] args) throws InterruptedException {
        Thread1 thread = new Thread1();
        thread.start();
//        thread.stop();
        Thread.sleep(1000);
//        thread.stopMe();
        thread.interrupt();
        
    }
}


(5) and wait for notification

  • A thread acquired the object xx monitor, called xx.wait () method, the thread A stops running into the waiting queue object xx, xx release objects monitor
  • Other threads get the object xx monitor, called xx.notify () method, from the xx object waiting in the queue randomly selected thread and wake up, release xx objects monitor
  • Other threads get the object xx monitor, called xx.notifyAll () method, all the threads waiting queue xx objects in the wake of the release of an object monitor xx

Will release resources held by waiting, it can be awakened by other threads!

public class WaitAndNotify {
    final static Object object = new Object();
    static class ThreadA extends Thread{

        private String name;

        public ThreadA(String name) {
            super(name);
            this.name = name;
        }

        @Override
        public void run() {
            synchronized (object){
                System.out.println(name+"持有了对象");
                try {
                    System.out.println("对象想等待了");
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(name+"又持有了对象");
            }
        }
    }
    static class ThreadB extends Thread{
        @Override
        public void run() {
            synchronized (object){
                System.out.println("B持有了对象");
                System.out.println("对象准备好了");
                object.notifyAll();
            }
        }
    }

    public static void main(String[] args) {
        //一个线程等待
//        ThreadA a = new ThreadA("A");
//        a.start();
//        ThreadB b = new ThreadB();
//        b.start();
        //多个线程等待
        ThreadA[] as = new ThreadA[5];
        for (int i = 0; i < 5; i++) {
            as[i] = new ThreadA("A"+i);
            as[i].start();
        }
        ThreadB b = new ThreadB();
        b.start();
    }
}

(6) suspend and resume execution

  • Should not be used thread.suspend () suspends the thread, because resources can not be released
  • Should not be used thread.resume () wake up the thread, if awakened before suspending, the thread will be permanently suspended
public class SuspendAndResume {

    static class ThreadA extends Thread {
        private boolean suspend = false;

        public void suspendMe() {
            System.out.println("挂起线程");
            suspend = true;
        }

        //唤醒线程——通知
        public void resumeMe() {
            System.out.println("唤醒线程");
            suspend = false;
            synchronized (this) {
                notify();
            }
        }

        @Override
        public void run() {
            while (true) {
                synchronized (this) {

                    //被挂起了——等待
                    while (suspend) {
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                        System.out.println("线程A开始工作");

                }
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadA a = new ThreadA();
        a.start();
        Thread.sleep(1000);
        a.suspendMe();
        Thread.sleep(1000);
        a.resumeMe();
    }
}


(7) wait for the end

By thread.join (), a thread needs to rely on the use of threads waiting thread is finished, you can proceed

  • join (): wait indefinitely until the target thread completes
  • join (time): Wait for some time, if the target thread has not been completed, then proceed
public class Join {
    static volatile int i = 0;
    static class ThreadA extends Thread{
        @Override
        public void run() {
            for (i = 0; i < 10; i++) {

            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadA a = new ThreadA();
        a.start();
        a.join();
        System.out.println(i);
    }
}

(8) humility

By Thread.yield (), so that a current thread CPU, and then re-compete.
Suitable for a low-priority, multi-thread CPU resources

3. Java keywords

(1) volatile keyword

Can guarantee the visibility of data and ordering can not be guaranteed atomicity

(2) synchronized keyword

Order and ensure visibility between atomic operations, thread

  • Designated lock object: the need to obtain a given lock of the object before entering the sync blocks
  • Examples of the method applied to: the need to obtain an instance of an object prior to entering the lock sync blocks
  • Acting on the static method: class lock is currently required to obtain sync blocks before entering

4. A thread's priority

Java is used 1-10 or three static variables indicating the priority, high-priority general advantage in competing for resources

  • Thread.MIN_PRIORITY
  • Thread.NORM_PRIORITY
  • Thread.MAX_PRIORITY
thread.setPriority(优先级);

5. Daemon daemon thread

  • Daemon threads: complete systematic task in the background (if only daemon threads, JVM will naturally withdraw)
  • User threads: complete the process of business operations
public class DaemonTest {
    static class Daemon extends Thread{
        @Override
        public void run() {
            while (true){
                System.out.println("我在进行后台工作...");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Daemon();
        //设置守护线程
        thread.setDaemon(true);
        thread.start();
        //休眠3秒后,主线程结束,所以守护线程也结束了
        Thread.sleep(3000);
    }
}

6. Thread Group

If the number of multi-threading, and features a clear, then thread the same function can be placed in a thread group

create

  • Thread Group: ThreadGroup group = new ThreadGroup (thread group name);
  • Add threads: Thread thread = new Thread (group, an interface thread, thread name);

use

  • Activities get the number of threads: System.out.println ( "current active thread:" + group.activeCount ());
  • Gets the number of threads in the thread group: group.list ()
public class ThreadGroupTest {
    static class Group implements Runnable{
        @Override
        public void run() {
            String group = Thread.currentThread().getThreadGroup().getName();
            String name = Thread.currentThread().getName();
            while (true){
                System.out.println(group+"--"+name);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args) {
        ThreadGroup group = new ThreadGroup("Test");
        Thread t1 = new Thread(group,new Group(),"Thread1");
        Thread t2 = new Thread(group,new Group(),"Thread2");
        t1.start();
        t2.start();
        System.out.println("当前活跃线程:"+group.activeCount());
        group.list();
    }
}

7. Java's collection

ArrayList replaced with Vector
with ConcurrentHashMap replaced HashMap

Guess you like

Origin blog.csdn.net/weixin_36904568/article/details/90339246