(10) concurrent programming based on the art of Java concurrent programming

Introduction Thread

Modern operating systems when running a program that will create a process. For example, start a Java program, the operating system will create a Java process.
Operating system process is the smallest unit that can be scheduled.
A process can contain multiple threads that have their own property counters, stack, and local variables, and can access shared variables.
A thread is the smallest unit of CPU resource allocation.

Thread priority

Modern operating systems run the basic form of a time-division scheduling threads, the operating system will be the separation of a time slice, the thread will be allocated to a number of time slices, the current thread's time slice runs out of thread scheduling occurs, and waiting for the next assignment . The thread assigned to the number of time slots will determine how many threads to use processor resources, while the thread priority thread is to decide how much or little need to allocate some thread attributes processor resources.

State of the thread

State Name Explanation
NEW The initial state, the thread is constructed, but also not called start () method
RUNNABLE Operating status, Java threads in the operating system is ready and running two states generically referred to as "running"
BLOCKED Blocking state, it indicates that the thread blocked on lock
WAITING Wait state, it indicates that the thread into a wait state, entering the state indicates that the current thread to wait for another thread to throw some specific action (notification or interrupt)
TIME_WAITING Timeout wait state, which is different from the WAITING state, it is free to return at a specified time
TERMINATED Termination state, indicates that the current thread has finished

You can use jstack tools, thread View running.
Here Insert Picture Description
After the thread is created, call the start () method starts running.
When the thread executing wait () method, the thread into a wait state. The thread into a wait state need to rely on other threads notice to be able to return to the running state and the timeout wait state is equivalent on the basis of wait states plus the timeout limit, the timeout is reached will be returned to operation.
When the calling thread synchronization method is that in the absence of acquired lock, the thread will enter the blocking state. After executing threads run Runnable () method will enter the final state.

Java will run the operating system and ready to run state called two states merged. When the blocking state when the state enters a keyword synchronized method or block of code modified (to obtain a lock) of the thread is blocked, but blocking Lock interface java.concurrent package thread state is waiting for the state, because java.concurrent package Lock Interface for blocking implementation are used LockSupport class associated methods.

Daemon threads

Daemon thread is a type of thread support, because it is mainly used as a background program scheduling and advocacy work. This means that when a non-Daemon thread does not exist a Java Virtual Machine, the Java virtual machine will exit. By calling Thread.setDaemon (true) Daemon thread to thread.
Daemon attributes required before starting the thread settings can not be set after starting the thread.

public class Daemon {
    public static void main(String[] args) {
        Thread thread = new Thread(new DaemonRunner(), "DaemonRunner");
        thread.setDaemon(true);
        thread.start();
    }

    static class DaemonRunner implements Runnable {
        @Override
        public void run() {
            try {
                SleepUtils.second(10);
            } finally {
                System.out.println("DaemonThread finally run.");
            }
        }
    }
}

Daemon program operation, no output can be seen on the terminal or the command prompt. main thread (non Daemon thread) finished as the main method is terminated after starting the thread DaemonRunner, at a time when the Java virtual machine has no non-Daemon threads, virtual machines need to quit. All Daemon thread Java virtual machine needs to be terminated immediately, so DaemonRunner terminated immediately, but DaemonRunner in the finally block is not executed.

When building Daemon thread, you can not rely on the contents of the finally block to ensure the implementation of logic resources to clean up or shut down.

Initiate and terminate the thread

By calling the thread start () method to start, with the execution run () method is completed, the thread will terminate

Construction thread
Start a thread

After initialization is complete thread object, call the start () method can be used to start this thread. Meaning thread start () method: the current thread synchronization inform the Java Virtual Machine, as long as the thread space planner should start immediately call the start () method thread.

Interrupt

Interrupt can be understood as a marking thread attribute bit, it marked a running thread is used by another thread was interrupted operations. Like other threads that thread interrupt hello, its other threads (0 interrupt the thread by calling the interrupt handling
thread itself by checking whether the interrupt respond by the method isInterrupted thread () determines whether to perform interrupt, you can also call the static method Thred.interrupted () to interrupt the current thread marking bit is reset. If the thread is already in the end of the state, even if the thread is interrupted, calling the thread object isInterrupted () will still return false

Communication between threads

Thread running, it has its own stack space, like a script as a step performed in accordance with established codes step until terminated.
the volatile keyword, the memory can guarantee the visibility of a single variable.
Modified volatile member variable, a thread after changes to the volatile variable, the variable will refresh this into the main memory, while the other thread cache invalidation, other threads that want to access the main memory to the volatile variables can only be read.
synchronized keyword, or by using a synchronous block form by modification of the method, which ensures that only one thread entry to this method, or a synchronization code blocks.
Any object has its own monitor
Here Insert Picture Description

Thread.join () use

If a thread A executed thread.join () statements:
the current thread A waits for thread after thread to terminate () returns from thread.join. Thread addition thread join (), also provides a join (long millis) and join (long millis, int nanos) includes a timeout feature of the two methods. These two methods timeout said that if the thread thread does not terminate within a given timeout period, then will return from the time-out method.
Examples

public class Join {
    public static void main(String[] args) throws Exception {
        Thread previous = Thread.currentThread();
        for (int i = 0; i < 10; i++) { // 每个线程拥有前一个线程的引用,需要等待前一个线程终止,才能从等待中返回
            Thread thread = new Thread(new Domino(previous), String.valueOf(i));
            thread.start();
            previous = thread;
        }
        TimeUnit.SECONDS.sleep(5);
        System.out.println(Thread.currentThread().getName() + " terminate.");
    }
    static class Domino implements Runnable {
        private Thread thread;

        public Domino(Thread thread) {
            this.thread = thread;
        }
        public void run() {
            try {
                thread.join();
            } catch (InterruptedException e) {
            }
            System.out.println(Thread.currentThread().getName() + " terminate.");
        }
    }
}
main terminate.
0 terminate.
1 terminate.
2 terminate.
3 terminate.
4 terminate.
5 terminate.
6 terminate.
7 terminate.
8 terminate.
9 terminate.

Can be seen from the output, provided for each thread to terminate the precursor thread, each thread waits precursor thread termination only after () method returns the join, this involves waiting / notification mechanism (thread waiting for the end of the precursor, receiving precursor thread end notification)

ThreadLocal

ThreadLocal, i.e. thread variable, is a key ThreadLocal object, the value of any object storage structure. The structures are shipped on a thread, that one thread can query to a value bound to this thread in accordance with a ThreadLocal object. Value can be set by a set (T) method, under the current thread acquired again by the get method previously set value ().

public class Profiler { // 第一次get()方法调用时会进行初始化(如果set方法没有调用),每个线程会调用一次 
    private static final ThreadLocal<Long> TIME_THREADLOCAL = new ThreadLocal<Long>() {
        protected Long initialValue() {
            return System.currentTimeMillis();
        }
    };

    public static final void begin() {
        TIME_THREADLOCAL.set(System.currentTimeMillis());
    }

    public static final long end() {
        return System.currentTimeMillis() - TIME_THREADLOCAL.get();
    }

    public static void main(String[] args) throws Exception {
        Profiler.begin();
        TimeUnit.SECONDS.sleep(1);
        System.out.println("Cost: " + Profiler.end() + " mills");
    }
}

Output

Cost: 1001 mills

Profiler can be multiplexed on the time-consuming method call statistics function, perform begin () method before entry method, do end after the method call () method, the advantage is not to call two methods in a method or class such as in AOP (aspect-oriented programming) and can be performed prior to the entry point method calls begin () method, and the execution end () method in the entry point after the method call, so you can still get time-consuming method.

Thread Pool

For server programs are often faced with a client incoming short (short execution time, job content more single) tasks that require fast processing server and return the results. If the server each time received a mandate to create a thread, and then execute, this is a good choice in the prototype stage, but the face of thousands of job submission time into the server, if a task or the use of a thread way , it will create tens of thousands of threads, this is not a good choice. This is because the operating system will be frequent thread context switching, no reason to increase the load on the system, and the thread creation and demise are consuming system resources, but also undoubtedly a waste of system resources.

Execution thread pool technology can solve this problem by a number of pre-created number of threads, and can not create a thread is controlled directly by the user, re-use fixed or relatively fixed number of threads in this context to complete the task . The advantage of this is that, on the one hand, eliminating the frequent thread creation and demise of system resource overhead, on the other hand, faced with the task of submitting excessive deterioration can be gentle.

Published 24 original articles · won praise 1 · views 542

Guess you like

Origin blog.csdn.net/qq_45366515/article/details/105153343