Talk about multithreading programming (a)--thread concept, multi-threading creation, daemon thread, thread state conversion

Source: Internet
Author: User
Tags thread class

1, what is the difference between threads and multithreading and process

When you run a program in modern operations, a process is created for it. For example, to start a QQ program, the operating system will create a process for it. The smallest unit in the operating system is a thread, also known as a lightweight process, in which multiple threads can be created, each with properties such as counters, stacks, and local variables, and access to shared memory variables. The processor switches on these threads at high speed, allowing the user to feel that these threads are executing simultaneously. So we can understand that:

Process: A running program that is a separate unit for resource allocation and invocation by the system. Each process has its own memory space and system resources.

Thread: is a single sequential control flow in a process and is an execution path. A process, if there is only one execution path, is called a single-threaded procedure. A process that has multiple execution paths is called a multithreaded program.

2, multi-threaded creation and startupThere are two ways to create multithreading, one is inheriting the thread class overriding the Run method, the other is implement Runnable Interface rewrite Run method。 Below we give the code example separately. Inherit the thread class to override the Run method:
 Package com.zejian.test;    Public class extends thread{      /**      * Rewrite the Run      method * /       @Override        Public void run () {          System.out.println ("I ' m a thread that extends thread!" );      }  }  

To implement the Runnable interface rewrite the Run method:

 Package com.zejian.test;    Public class Implements runnable{      /**      * Implement the Run      method * /       @Override        Public void run () {          System.out.println ("I ' m a thread that implements Runnable!") );      }  

How do I start a thread?

 Packagecom.zejian.test;  Public classMaintest { Public Static voidMain (string[] args) {//inherited thread-initiated methodsThreadbyex t1=NewThreadbyex (); T1.start ();//Start Thread//ways to implement runnable startup threadsThreadbyrunnable r =Newthreadbyrunnable (); Thread T2=NewThread (R); T2.start ();//Start Thread    }  }

Operation Result:

I ' m a thread that extends thread!  

It is important to note that the start () method is not immediately followed by the execution of multithreaded code, but rather to make the thread operational, and when to run multithreaded code is determined by the operating system.

3. Daemon thread and Thread priority

Daemon Thread:

First, we can convert a thread to a daemon thread by T.setdaemon (true). The only role of the daemon is to serve other threads. A timed thread is a typical example that periodically sends a "timer tick" signal that tells other threads to perform a task. When only the daemon is left, the virtual machine exits, because if only the daemon is left, the program does not need to be executed. In addition, the JVM's garbage collection, memory management and other threads are the daemon thread. There is in the database application, the use of the database connection pool, the connection pool itself contains a lot of background threads, monitoring the number of connections, time-out, status, and so on. Finally, it is important to note that the finally code block in the daemon thread is not necessarily executed when the Java virtual machine exits, and the code example:

 Packagecom.zejian.test;  Public classDemon { Public Static voidMain (string[] args) {Thread Deamon=NewThread (NewDaemonrunner (), "Daemonrunner"); //Set as daemon threadDeamon.setdaemon (true); Deamon.start ();//Start Thread    }                 Static classDaemonrunnerImplementsrunnable{@Override Public voidrun () {Try{Thread.Sleep (500); } Catch(interruptedexception e) {e.printstacktrace (); }finally{System.out.println ("The code here does not necessarily execute when the Java virtual machine exits!" "); }          }      }  }  

Therefore, when building daemon threads, you cannot rely on the contents of the finally code block to ensure that the logic to close or clean up resources is executed.

Priority of the thread:

In the modern operating system, the basic use of time-division in the form of scheduling running threads, the operating system will be divided into a number of times slices, the thread will be allocated to several time slices, when the thread time slice run out will occur thread scheduling, and waiting for the next allocation. The time slices allocated to a thread also determine how much the thread uses the processor resources, and the thread priority is the thread attribute that determines how many or less of the processor resources the thread needs to allocate. In a Java thread, the thread priority is controlled through the member variable precedence of an integral type.

Each thread has a priority, and by default, a thread inherits its parent class's priority. You can use the SetPriority method to increase or decrease the priority of any thread. You can set the priority to any value between min_priority (defined as 1 in the thread Class) and max_priority (defined as 10 in the thread Class). The default priority for threads is norm_priority (defined as 5 in the thread Class).

Try not to rely on priority, and if you do, avoid a mistake that beginners often make. If there are several high-priority threads that are not inactive, a low-priority thread may never be able to execute. Whenever the scheduler decides to run a new thread, the first choice is made in a thread with a high priority, although this causes the low-priority thread to never be executed. Therefore, when we set the priority, the threads that are targeted for frequent blocking (hibernation or I/O operations) need to have a higher priority, while threads that favor computation (which requires more CPU time or arithmetic) set a lower priority to ensure that the processor is not permanently monopolized. Also note that there are differences in the planning of different JVMs and operating system threads, and some operating systems even ignore thread priority settings such as Mac OS system or Ubuntu system ...

4, the State of the thread transition relationship

(1) new State: A new Thread object was created.

(2) ready State (Runnable): After the thread object is created, other threads call the object's start () method . The state of the thread is located in a pool of running threads that becomes operational and waits for the CPU to be used.

(3) running State (Running): The ready state of the thread gets the CPU, executes the program code.

(4) blocking state (Blocked): The blocking state is that the thread abandons the CPU for some reason and temporarily stops running . Until the thread is in a ready state, the opportunity to go to the running state is reached. There are three types of blocking:

- wait for blocking (waiting): The running thread executes the Wait () method , and the JVM puts the thread into the waiting pool.

- Synchronous Blocking (Blocked): When a running thread acquires a synchronization lock on an object , the JVM puts the thread into the lock pool if the synchronization lock is occupied by another thread .

- Timeout blocking (time_waiting): The running thread executes the sleep (long) or join (long) method , or when an I/O request is made , the JVM will place the thread in a blocked state.

(5) death status (Dead): The thread finishes executing or exits the run () method due to an exception , and the thread ends the life cycle.

The method in the figure is resolved as follows:
Thread.Sleep (): Allows the currently executing thread to pause execution for a specified period of time, but does not release the lock flag. It is not recommended.
Thread.Sleep (Long): Causes the current thread to enter a blocking state that will not be executed within a specified time.
object.wait ()Andobject.wait (Long)causes the current thread to wait before another thread calls the object's notify or Notifyall methodThe thread releases the "lock flag" that it occupies, allowing other threads to seize the lock。 The current thread must have the current object lock, which throws a Illegalmonitorstateexception exception if the current thread is not the owner of the lock.The waiting thread that wakes the current object lock uses the Notify or Notifyall method, and must also have the same object lock, or it throws a Illegalmonitorstateexception exception,Wait () and notify () must be called in the synchronized function or synchronized。 If the call is made in the non-synchronized function or non-synchronized, the illegalmonitorstateexception exception will occur at run time, although it can be compiled.
Object.notifyall (): Wakes all waiting threads from the object waiting pool
object.notify (): Wakes one of the threads from the object waiting pool.
Thread.yield (): Pauses the currently executing thread object, and yield () simply returns the current thread back to the executable state, so that the thread executing yield () is likely to be executed immediately after entering the executable state, and yield () can only cause the thread with the same priority or higher priority to have an opportunity to execute.
Thread.Join (): Adding the specified thread to the current thread, you can merge two alternately executed threads into sequentially executed threads. For example, thread A's join () method is called in Threads B, and thread B is not resumed until thread a finishes execution.

Talk about multithreading programming (a)--thread concept, multi-threading creation, daemon thread, thread state conversion

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.