Java multi-thread programming Summary

Source: Internet
Author: User
Tags time in milliseconds
Java multi-thread programming summary below is a cataloguing of the Java thread series blog: Java thread: concept and principle Java thread: Create and start Java thread: thread stack model and thread variable Java thread: conversion of thread status Java thread: synchronization and lock of thread Java thread: Interaction of thread Java thread: Thread Scheduling-sleep Java thread: Thread Scheduling-priority Java thread: thread Scheduling-concession Java thread: Thread Scheduling-merge Java thread: Thread Scheduling-daemon thread Java thread: thread synchronization-synchronization method Java thread: thread Synchronization-synchronization block Java thread: Concurrent collaboration-producer consumer model Java thread: Concurrent collaboration-deadlock Java thread: Volatile keyword Java thread: New features-thread pool Java thread: new features-threads with returned values

Java thread: new feature-lock (on)

Java thread: new feature-lock (lower) Java thread: new feature-semaphore Java thread: new feature-blocking queue Java thread: new feature-blocking stack Java thread: new Feature-Conditional Variable Java thread: new feature-atomic Java thread: new feature-Barrier

Java thread: In summary, the content below the thread was written a long time ago. The content is not full enough and is based on Java. After Java 5, thread concurrency has extended a considerable amount of content, therefore, we suggest you read the content of the above series of articles to keep up with the times and keep up with the pace of Java development. I. To understand multi-task, multi-process, single-thread, and multi-thread, to understand multithreading, we must start with the operating system principle. In the past, the old DOS Operating System (V 6.22) was single-task and there was no thread concept. The system could only do one thing at a time. For example, you cannot rename the file name when copying objects. To improve the utilization efficiency of the system, batch processing is used to execute tasks in batches. The current operating system is a multi-task operating system, and each running task is a task done by the operating system. For example, you are still using MSN to chat with friends while listening to songs. Listening to songs and chatting are two tasks. These two tasks are "simultaneously. A task generally corresponds to a process and may contain several processes. For example, the running MSN corresponds to an MSN process. If you are using a Windows system, you can view the information of the running process of the operating system in the task manager. Generally, a process is started when an application is running. Of course, several processes are started. When a process is started, the operating system allocates resources to the process. The most important resource is the memory space because the program runs in the memory. In the process, some program flow blocks can be executed in disorder, and the code block can be executed multiple times at the same time. In fact, such a code block is the thread body. A thread is a code flow executed in disorder. When multiple threads run simultaneously, this execution mode becomes concurrent execution. Multithreading aims to maximize the use of CPU resources. Java programming programs run in the Java Virtual Machine (JVM). In the JVM, the multi-task of the program is implemented through the thread. Every time you start a Java application with a Java command, a JVM process is started. In the same JVM process, there is only one process itself. In this JVM environment, all program code runs in threads. Common Java applications are single-threaded. For example, when the Java command is used to run the simplest helloworld Java application, a JVM process is started. The JVM finds the main () entry point of the program, and then runs main () in this way, a thread is generated, which is called the main thread. After the main method is completed, the main thread runs completely. The JVM process also exits. For multiple threads in a process, multiple threads share the memory block of the process. When a new thread is generated, the operating system does not allocate new memory, instead, let the new thread share the memory of the original process block. Therefore, inter-thread communication is easy and fast. Because different processes are in different memory blocks, communication between processes is relatively difficult. In fact, the multi-process of the operating system achieves multi-task concurrent execution, and the multi-thread of the program implements concurrent execution of the process. Multi-task, multi-process, and multi-thread support is required for the operating system. In Java programs, JVM is responsible for thread scheduling. Thread Scheduling is to assign the CPU usage right to multiple threads according to the specific mechanism. There are two scheduling modes: time-based scheduling and preemptible scheduling. Time-based scheduling allows all threads to get the CPU usage in turn and evenly allocate the CPU usage time for each thread. preemptible scheduling obtains the CPU usage right based on the priority of the thread. The thread scheduling mode of JVM adopts the preemptible mode. The so-called "concurrent execution" and "at the same time" are not actually "at the same time" in the true sense ". As we all know, the CPU has a clock frequency, indicating the number of times that CPU commands can be executed per second. In each clock cycle, the CPU can only execute one (or more) command. The operating system manages the process threads, distributes each process in turn (without a fixed order) for a short period of time (not necessarily equal), and then inside each thread, the program code processes the time allocation of internal threads of the process by itself, and multiple threads are switched to each other for execution. This switching time is also very short. Therefore, multi-task, multi-process, and multi-thread operations are a kind of macro feeling provided by the operating system. From a micro perspective, the program runs asynchronously. Summary in one sentence: although the operating system is multi-threaded, the CPU can only do one thing at a time, which is the same as the human brain. 2. multithreading of Java and multithreading Java requires support from the operating system. Java Virtual Machine allows applications to run multiple execution threads concurrently. The Java language provides extensions for multi-threaded programming and provides powerful thread control APIs. In Java, multithreading can be implemented in two ways: Java extension. lang. java. lang. each thread of the runnable interface has a priority. The execution of a high-priority thread takes precedence over that of a low-priority thread. Each thread can or cannot be marked as a daemon. When the code running in a thread creates a new thread object, the initial priority of the new thread is set to the priority of the Creation thread, and only when the creation thread is a daemon thread, the new thread is the daemon. When a Java Virtual Machine is started, there is usually a single non-daemon thread (it usually calls the main method of a specified class ). Java virtual opportunity continues to execute the thread until any of the following circumstances occurs: the exit method of the runtime class is called, and the security manager allows the exit Operation to occur. All threads of non-daemon threads have stopped running, whether returned by calling the run method or by throwing an exception outside the run method. Iii. Extend the java. Lang. Thread class

Package thread;/*** file name: testmitithread. java * created by: intellij idea. * copyright: Copyright (c) 2003-2006 * company: lavasoft ([url] cached) * Author: leizhimin * modifier: leizhimin * Date Time: 10:03:12 * readme: implement multithreading by extending the Thread class */public class testmitithread {public static void main (string [] rags) {system. out. println (thread. currentthread (). getname () + "Thread running starts! "); New mitisay (" "). start (); New mitisay ("B "). start (); system. out. println (thread. currentthread (). getname () + "the thread stops running! ") ;}} Class mitisay extends thread {public mitisay (string threadname) {super (threadname);} public void run () {system. out. println (getname () + "the thread starts running! "); For (INT I = 0; I <10; I ++) {system. out. println (I + "" + getname (); try {sleep (INT) math. random () * 10);} catch (interruptedexception e) {e. printstacktrace () ;}} system. out. println (getname () + "the thread stops running! ");}}

Running result:

The main thread starts running! Thread a starts running! The main thread is running! Thread B starts running! 0 A0 B1 A1 B2 A2 B3 A3 B4 A4 B5 B6 B5 A7 B6 A8 B7 A9 B8 AB thread running is complete! 9. The aa thread is running!

Note: When the program starts to run main, the Java Virtual Machine starts a process. The main thread is created when main () is called. With the start method of the two objects called by mitisay, the other two threads are started, so that the entire application runs under multiple threads. Call the thread. currentthread (). getname () method in a method to obtain the name of the current thread. Call this method in the mian method to obtain the name of the main thread. Note: After the start () method is called, it does not execute multi-threaded code immediately, but changes the thread to a runnable state. It is determined by the operating system when the thread runs. The results of running the program show that multi-threaded programs are executed in disorder. Therefore, it is necessary to design the code in disorder into multiple threads. The thread. Sleep () method is called to prevent the current thread from occupying the CPU resources obtained by the process independently, so as to set aside some time for other threads to execute. In fact, the execution sequence of all multi-threaded code is uncertain, and the results of each execution are random. 4. Implement the java. Lang. runnable interface

Package thread;/*** implement multiple threads through the runnable interface */public class testmitithread1 implements runnable {public static void main (string [] ARGs) {system. out. println (thread. currentthread (). getname () + "the thread starts running! "); Testmitithread1 test = new testmitithread1 (); thread thread1 = new thread (TEST); thread thread2 = new thread (TEST); thread1.start (); thread2.start (); system. out. println (thread. currentthread (). getname () + "the thread stops running! ");} Public void run () {system. Out. println (thread. currentthread (). getname () +" the thread starts running! "); For (INT I = 0; I <10; I ++) {system. out. println (I + "" + thread. currentthread (). getname (); try {thread. sleep (INT) math. random () * 10);} catch (interruptedexception e) {e. printstacktrace () ;}} system. out. println (thread. currentthread (). getname () + "the thread stops running! ");}}

Running result: the main thread starts to run! Thread-0 thread running starts! The main thread is running! 0 Thread-0Thread-1 thread run started! 0 thread-11 thread-11 thread-02 thread-02 thread-13 thread-03 thread-14 thread-04 thread-15 thread-06 thread-05 thread-17 thread-08 thread-06 thread-19 thread-07 Thread-1Thread-0 thread running ended! 8 thread-19 Thread-1Thread-1 thread running ended! Note: The testmitithread1 class implements the runnable interface so that the class has the features of the multithreading class. The run () method is a convention for multi-threaded programs. All the multi-threaded code is included in the run method. The thread class is actually a class that implements the runnable interface. When starting multithreading, you must first construct an object through the Thread class constructor thread (runnable target), and then call the START () method of the thread object to run the multi-thread code. In fact, all multithreading code is run by running the START () method of thread. Therefore, no matter whether the Thread class is extended or the runnable interface is implemented to implement multithreading, the thread object API is used to control the thread. The APIS familiar with the Thread class are the basis for multithreading programming. 5. The highest priority that a thread-class API static int max_priority thread can have. The lowest priority that a static int min_priority thread can have. The default priority that the static int norm_priority assigns to the thread. Constructor summary thread (runnable target) allocates a new thread object. Thread (string name) allocates a new thread object. Method abstract static thread currentthread () returns a reference to the currently executed thread object. Classloader getcontextclassloader () returns the context classloader of the thread. Long GETID () returns the identifier of the thread. String getname () returns the name of the thread. Int getpriority () returns the priority of the thread. Thread. State getstate () returns the state of the thread. Threadgroup getthreadgroup () returns the thread group to which the thread belongs. Static Boolean holdslock (Object OBJ) returns true only when the current thread keeps the monitor lock on the specified object. Void interrupt () interrupt thread. Static Boolean interrupted () to test whether the current thread has been interrupted. Boolean isalive () is used to test whether the thread is active. Boolean isdaemon () to test whether the thread is a daemon thread. Boolean isinterrupted () to test whether the thread has been interrupted. Void join () waits for the thread to terminate. Void join (long millis) waits for the thread to terminate for a maximum of millis milliseconds. Void join (long millis, int Nanos) waits for the thread to terminate for a maximum of millis milliseconds + Nanos nanoseconds. Void resume () is out of date. This method is only used with suspend (), but suspend () has been opposed because it has a deadlock tendency. For more information, see why thread. Stop, thread. Suspend, and thread. Resume are opposed ?. Void run () if the thread is constructed using an independent runnable running object, the run method of the runnable object is called; otherwise, the method does not perform any operation and returns the result. Void setcontextclassloader (classloader Cl) sets the context classloader of the thread. Void setdaemon (Boolean on) marks the thread as a daemon or user thread. Static void setdefaultuncaughtexceptionhandler (thread. uncaughtexceptionhandler EH) sets the default handler called when the thread suddenly terminates because no exception is caught and no other handler is defined for the thread. Void setname (string name) changes the thread name to be the same as the parameter name. Void setpriority (INT newpriority) changes the priority of a thread. Void setuncaughtexceptionhandler (thread. uncaughtexceptionhandler EH) sets the handler called when the thread suddenly terminates due to exceptions not caught. Static void sleep (long millis) slews the currently running thread (paused) within a specified millisecond ). Static void sleep (long millis, int Nanos) slews the currently running thread (paused) within the specified millisecond plus the specified nanoseconds ). Void start () enables the thread to start execution; Java Virtual Machine calls the run method of the thread. Void stop () is out of date. This method is inherently insecure. Terminating a thread with thread. Stop will release all the monitors it has locked (as a natural consequence of uncheckthreaddeath exceptions that are propagated up the stack ). If any object previously protected by these monitors is in an inconsistent state, the corrupted object will be visible to other threads, which may lead to arbitrary behavior. Many use of stop should be replaced by code that modifies only some variables to indicate that the target thread should stop running. The target thread should regularly check the variable, and if the variable indicates that it is to stop running, return the result from its running method in sequence. If the target thread waits for a long time (for example, based on a condition variable), use
Interrupt method to interrupt the wait. For more information, see why do you disagree with thread. Stop, thread. Suspend, and thread. Resume? Void stop (throwable OBJ) is out of date. This method is inherently insecure. For more information, see stop. The additional danger of this method is that it can be used to generate exceptions not to be processed by the target thread (including checked exceptions that are unlikely to be thrown if this method is not available ). For more information, see why thread. Stop, thread. Suspend, and thread. Resume are opposed ?. Void suspend () is out of date. This method has been opposed because it has an inherent deadlock tendency. If the target thread remains locked on the monitor that protects key system resources when it is suspended, no thread can access the resource until the target thread starts again. If the thread that re-starts the target thread wants to lock the monitor before calling resume, a deadlock will occur. Such deadlocks often prove that they are "Frozen" processes. For more information, see why thread. Stop, thread. Suspend, and thread. Resume are opposed ?. String tostring () returns the string representation of the thread, including the thread name, priority, and thread group. Static void yield (): Pause the currently executing thread object and execute other threads. 6. The status of the thread changes under certain conditions. The following figure shows the State Conversion of thread changes: 1. New State (new): A New thread object is created. 2. ready state (runnable): After a thread object is created, other threads call the START () method of the object. The thread in this status is located in the runable thread pool and becomes runable, waiting to obtain the CPU usage right. 3. Running status (running): The ready thread obtains the CPU and executes the program code. 4. Blocking status (BLOCKED): the blocking status indicates that the thread gives up CPU usage for some reason and stops running temporarily. It is not until the thread enters the ready state that it has the opportunity to go to the running state. Blocking is divided into three types: (1) waiting for blocking: The Running thread executes the wait () method, and the JVM puts the thread into the waiting pool. (2) Synchronization blocking: When a running thread acquires the synchronization lock of an object, if the synchronization lock is occupied by another thread, the JVM puts the thread into the lock pool. (3) Other blocking: When the running thread executes the sleep () or join () method or sends an I/O Request, JVM sets the thread to blocking. When the sleep () status times out, the join () waits for the thread to terminate or times out, or the I/O processing is completed, the thread enters the ready state again. 5. Dead: When the thread is finished or the run () method is exited due to an exception, the thread ends its lifecycle. VII. Thread Scheduling 1. Adjust the thread priority: Java threads have a priority, and threads with a higher priority will receive more running opportunities. The Java thread priority is represented by an integer. The value range is 1 ~ 10. The Thread class has three static constants: the maximum priority that a static int max_priority thread can have. The value is 10. The lowest priority that a static int min_priority thread can have. The value is 1. The default priority that the static int norm_priority assigns to the thread. The value is 5. The setpriority () and getpriority () Methods of the thread class are used to set and obtain the thread priority respectively. Each thread has a default priority. The default priority of the main thread is thread. norm_priority. The thread priority has an inheritance relationship. For example, if thread B is created in thread a, thread B has the same priority as thread. JVM provides 10 thread priorities, but it cannot be well mapped with common operating systems. If you want the program to be transplanted to various operating systems, you should only use the Thread class with the following three static constants as the priority, so as to ensure that the same priority uses the same scheduling method. 2. Thread sleep: The thread. Sleep (long millis) method turns the thread into a blocking state. The millis parameter sets the sleep time in milliseconds. After sleep, the system changes to the ready state. The sleep () platform has good portability. 3. Thread wait: The wait () method in the object class causes the current thread to wait until other threads call the notify () method or yyall () Wake-up method of the object. These two wake-up methods are also methods in the object class, and the behavior is equivalent to calling wait (0. 4. Thread concession: The thread. Yield () method is used to pause the currently being executed thread object and give the execution opportunity to the same or higher priority thread. 5. Thread addition: Join () method, waiting for other threads to terminate

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.