# Preface: By reading the "Reading Java Concurrent series" is divided into4Coarse,9Section # #1.Concurrency Basics ###1) Basic use of threads ##2.Concurrency Principles ###2) Concurrency features ###3) volidate,synchronized###4CAS principle and atomic operation ###5AQS Principle ##3.Concurrency tools section ###6Thread pooling principle and use ###7Blocking queues and practical applications ###8Principles and applications of concurrent containers ###9) CopyOnWrite meaning and usage scenario ##4.Concurrent combatCopy the code

1. Concurrency Basics

1) Basic use of threads

  1. Thread states and transitions
  2. Multithreaded writing
  3. Thread groups and thread priorities

1. Thread states and transitions

The status of Java threads can be queried using enum thread. State

public enum State {
    NEW,/ / new
    RUNNABLE,// Run status
    BLOCKED,// Block
    WAITING,// Wait state
    TIMED_WAITING,// The wait times out. The wait ends when the TIME exceeds
    TERMINATED// Run complete
}
Copy the code

Several methods for threads

wait();// make the thread in a wait state
stop();// Stop the thread
terminated();
Copy the code

2. Multi-threaded writing

  • Studying multithreading, how to start a thread?
  • What is the difference between starting a Thread with Runnable, Thread, Callable, or ThreadPoolExecutor? What is Future?

First, start a thread


/ * * *@author: Little Prince Kava, nuggets *@date: Created in 2021/4/12 10:09 PM *@descriptionCreate thread demo *@modified By:
 * @version: $
 */
public class CreateThreadDemo {

    public void useThread(a) {
        Thread t = new Thread("Thread");
    }

    public void useRunnable(a) {
        Thread t = new Thread(() -> {
            System.out.println("Create thread with runnable");
        });
    }
    // Because Callable is used in the Executor framework, Callable is used in conjunction with thread pools
    public void useCallable(a) {
        Callable callable = () -> {
            System.out.println("Create thread by Callable");
            return null;
        };
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(15.35.25,
                TimeUnit.SECONDS, new ArrayBlockingQueue(5000)); threadPool.submit(callable); }}Copy the code

Callable allows us to catch exceptions and get the thread’s return result, but the return result is wrapped in the Future. We can get the thread’s execution result by calling the future.get() method, but this method blocks the thread.

3. Thread groups and thread priorities

ThreadGroup is a class that provides unified management of threads. It contains subthread groups and threads. It is a top-down structure, but is not recommended. Thread priority represents the value of a thread, and a thread with a high value has a high probability of being executed by the CPU first. Thread setPriority(int num) ranges from 1 to 10. The priority of the parent thread is not set by default