Java multi-thread--processes and threads

Source: Internet
Author: User

Java multi-thread-process and thread conceptual processes
    • The dynamic execution process of the program
    • Include Resources (memory, CPU) and threads that are occupied
Thread
    • A thread is the smallest execution unit in a program
    • A process has multiple threads
    • Resources for thread-sharing processes
Process and thread differentiation

We can imagine that a process is a class and a thread is every student in the state of Qi.

Interaction between threads
    • Mutual exclusion, similar to every student for the first place and you argue with me let, threads also, want to seize CPU resources
    • Synchronization, when the games are held, we all unite, share their resources with each other
Thread, Runnablethreadintroduction

Thread is the threads in Java, the thread is a program's multiple execution path, the execution of the dispatch unit, relying on the process exists. The thread can not only share the memory of the process, but also have a memory space of its own, which is also called the line stacks, which is allocated by the system when the thread is established, and is used primarily to hold the data used internally by the thread, such as variables defined in the thread execution function. Note: Multithreading in Java is a preemption mechanism rather than a time-sharing mechanism. Preemption refers to having multiple threads in a running state, but only one thread is allowed to run, and they preempt the CPU in a competitive way.

Define
/** * 使用继承java.lang.Thread类的方式创建一个线程 *  * @author DreamSea 2011-12-29 20:17:06 */publicclass ThreadTest extends Thread {    /**     * 重写(Override)run()方法 JVM会自动调用该方法     */    publicvoidrun() {        System.out.println("I‘m running!");    }}

Note that the override run() method is called after the thread's start() method, but the overloaded (overload) run() method, like a normal member method, does not run automatically by the JVM because it calls the thread's start() method.

public   Class  threadtest  extends  thread  { /** * override (Override) run () method The JVM automatically calls the method */  @Override  public  void  run  () {System.out.println ( "I ' m running!" ); } /** * Overload (Overload) The run () method is the same as the normal method, and will not be run automatically by the JVM after the start () method of the thread is called */  public void  run  ( Span class= "Hljs-keyword" >int times) {System.out.println (  "I" M running! ( Overload) "); }} 

Usage recommendations

This method is not recommended because the class inherits from the thread and cannot inherit other classes, and the implementation of this method is different from the implementation of the Runnable interface.

Start
thread=new ThreadTest();thread.start();
State
    • new State (new): When an instance of a thread is created using the new keyword and the thread class or its subclasses to create a threaded object, the thread is in the new state, and the new state of the thread has its own memory space, but the thread is not running. The thread is not alive at this time (not alive);

    • ready State (Runnable): Initiates a thread to the Ready state (Runnable) by invoking the start () method of the thread instance, and the thread in the ready state is already running, but not yet assigned to the CPU, which is not necessarily immediately executed. At this point in the thread-ready queue, waiting for the system to allocate CPU, waiting state is not the execution state, at this time the thread is alive (alive);

    • blocking State (Blocked): The thread is in a blocked (Blocked) state by calling join (), sleep (), wait (), or a resource being taken up; the thread in blocking state is still alive (alive);

    • dead State (Dead): When a thread's run () method is finished or is interrupted or exited abnormally, the thread reaches the dead (Dead) state. There may still be an instance object of that thread, and the thread's independent call stack has been dissolved when it is not possible to be treated as a thread that can be executed independently. Once a thread enters the dead state, he can no longer enter the life cycle of a separate thread. For a thread in the dead state, the start () method is called, and an exception is run (runtime exception), and the thread in dead state is not alive (not alive).

    • thread life cycle : The new object is then executed by Thread.Start (), runnable, after the JVM dispatches the CPU resources to running state, finally dies, the intermediate threads may be blocked or not dispatched.

Context

For a single-core CPU (for multicore CPUs, this is understood here as a core), the CPU can only run one thread at a time, and when the process of running one thread goes to run another thread, this is called a thread-context switch (similar to a process).

Since it is possible that the task of the front-end process is not completed, the running state of the thread needs to be saved during the switchover so that it can continue to run until the next switch back. To give a simple example: a thread A is reading the contents of a file, is reading half of the file, the need to pause thread A, go to execute thread B, when the switch back to execute thread A, we do not want thread A again from the beginning of the file to read.

So you need to record the running state of thread A, what data is logged? Because the next time you need to know which command the current thread has executed before, you need to log the value of the program counter, and if the thread is suspended while a calculation is in progress, the next time you continue execution you need to know what the value of the variable was when it was suspended, so you need to record the status of the CPU register. So in general, the program counters, CPU register status and other data are recorded during thread context switching.

To put it simple: context switching for threads is actually the process of storing and recovering CPU state, which enables thread execution to resume execution from a breakpoint.

While multi-threading can improve the efficiency of task execution, there are also some overhead costs associated with thread switching, and multiple threads can lead to increased system resource usage, so be aware of these factors in multithreaded programming.

Function
category method Signature Introduction
thread creation thread ()
threading Creation thread (String name
thread creation thread (Runnable Runnable)
Thread creation thread (Runnable target, String name)
thread method start () start thread
thread method static void sleep (long Millis) hibernate thread
method of Thread static void Sleep (long millis, int nanos) Dormant Threads
thread method void Join () causes other threads to wait for the current thread to terminate
thread method void join (Long Millis) causes other threads to wait for the current thread to terminate
thread method void Join (long millis, int nanos) causes other threads to wait for the current thread to terminate
Get available threads static Thread CurrentThread () returns a reference to the currently running thread
Note:
    • Sleep is the equivalent of having a thread sleeping, handing over the CPU, and allowing the CPU to perform other tasks.
      However, it is important to note that the sleep method does not release the lock, which means that if the current thread holds a lock on an object, other threads cannot access the object even if the sleep method is called.
 Public  class Test implements Runnable {    @Override     Public void Run(){ This. s (); } Public synchronized void s() {System.out.println (Thread.CurrentThread (). GetName () +"get lock.");Try{Thread.Sleep ( +); }Catch(Interruptedexception e)        {E.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () +"release lock."); } Public Static void Main(string[] args) {Test St =NewTest (); Thread T1 =NewThread (St,"T1"); Thread t2 =NewThread (St,"T2");         T1.start ();    T2.start (); }}

His output data is:

T1 get lock.

T1 release lock.

T2 get lock.

T2 release Lock.

    • The yield method calls the yield method to have the current thread hand over the CPU permissions, allowing the CPU to execute other threads. It is similar to the sleep method and does not release the lock. However, yield does not control the specific time to hand over the CPU, and the yield method only allows threads with the same priority to have the opportunity to get CPU execution time.

    • The wait method causes the thread to go into a blocking state, releasing the lock that the thread occupies and handing over the CPU execution permissions.
      Because the wait method causes the thread to release the object lock, the Join method also causes the thread to release locks held on an object. The specific wait method is used in the following article.

 Public  class Test1 implements Runnable {    PrivateObject lock; Public Test1(Object Lock) { This. lock = lock; }@Override     Public void Run(){synchronized(lock) {System.out.println (Thread.CurrentThread (). GetName () +"get lock.");Try{lock.wait (); }Catch(Interruptedexception e)            {E.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () +"release lock."); }    }}
 Public classTest2 implements Runnable {PrivateObjectLock; Public Test2(ObjectLock){ This.Lock=Lock; } @Override Public void Run() {Try{Thread.Sleep (2* +); }Catch(Interruptedexception e)        {E.printstacktrace (); } synchronized (Lock) {System. out. println (Thread.CurrentThread (). GetName () +"get lock.");Lock. Notifyall (); System. out. println (Thread.CurrentThread (). GetName () +"release lock."); } synchronized (Lock) {System. out. println (Thread.CurrentThread (). GetName () +"get lock."); System. out. println (Thread.CurrentThread (). GetName () +"release lock."); }    } Public Static void Main(string[] args) {ObjectLock=NewObject (); Thread T1 =NewThread (NewTest1 (Lock),"T1"); Thread t2 =NewThread (NewTest2 (Lock),"T2");        T1.start ();    T2.start (); }}

The results are as follows:

T1 get lock.

T2 get lock.

T2 release Lock.

T2 get lock.

T2 release Lock.

T1 release lock.

    • Interrupt method Interrupt, as the name implies, is the meaning of interruption. Calling the interrupt method alone can cause a blocked thread to throw an exception, which can be used to break a thread that is in a blocking state, and to stop a running thread by using the interrupt method and the Isinterrupted () method.
Runnabledefinie

A class can also be implemented by implementing the Java.lang.Runnable interface if it needs to be capable of multithreading. According to the syntax of the Java language, a class can implement any number of interfaces, so the implementation of this way in the actual implementation of the commonality is better than the way described earlier. However, the separate run method cannot be executed asynchronously, that is, calling the Run method directly is not the same as the result of the thread calling the Run method.

Difference of

Take the ticket purchase procedure as an example, when we use runnable to implement multi-threading

 Public  class runnabletest implements Runnable{     Public Static intCount =Ten; PublicString name; Public runnabletest(String name) { This. name = name; }@Override     Public void Run() { while(Count >0) {count--; Print"Thread:"+ name +"And now there's the"+ Count +"Ticket!"); }    } Public Static void Main(String args[]) {Runnabletest Test1 =NewRunnabletest ("Little Red"); Runnabletest test2 =NewRunnabletest ("Little Green"); Runnabletest test3 =NewRunnabletest ("Little Blue");NewThread (test1). Start ();NewThread (Test2). Start ();NewThread (TEST3). Start (); } Public Static void Print(Object o)    {System.out.println (o.tostring ()); }}

The output is:

Thread: Little Red, now there are 9 tickets!

Thread: Little Red, now there are 6 tickets!

Thread: Little blue, now there are 7 tickets!

Thread: Little blue, now there are 4 tickets!

Thread: Small green, now there are 8 tickets!

Thread: Little blue, now there are 3 tickets!

Thread: Little Red, now there are 5 tickets!

Thread: Little blue, now there are 1 tickets!

Thread: Small green, now there are 2 tickets!

Thread: Little Red, now there are 0 tickets!

when we use thread, however, the results are different:
Thread: Little Red, now there are 8 tickets!

Thread: Little blue, now there are 7 tickets!

Thread: Small green, now there are 7 tickets!

Thread: Little blue, now there are 5 tickets!

Thread: Little Red, now there are 6 tickets!

Thread: Little blue, now there are 3 tickets!

Thread: Small green, now there are 4 tickets!

Thread: Little blue, now there are 1 tickets!

Thread: Little Red, now there are 2 tickets!

Thread: Small green, now there are 0 tickets!

It can be seen that duplicate data, which is the difference between runnable and thread in different implementations, is because the inherited thread does not guarantee the visibility of shared data, as to what is shared data, how to share data, we will say next time

Java multi-thread--processes and threads

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.