"Java Core technology Volume One" notes multithreading

Source: Internet
Author: User

Sometimes we need to work on multiple tasks in parallel in one program, such as playing music on the player while constantly updating the screen display, or performing time-consuming tasks while the UI continues to respond to various events. There are times when a task takes a long time to complete, and if it is executed in multiple parts, it can greatly shorten the time required. Multithreading can be a good solution to this kind of problem.

A program (process) If you can perform multiple tasks at the same time, each parallel task is done through a thread, which is a multithreaded program. The process has its own set of data (variables), each thread shares the process's data, the inter-thread communication is simpler than interprocess communication, and the thread overhead is smaller than the process.

There are many classes available in Java for multi-threaded tasks. Includes the most basic thread classes, runnable, and other interfaces for thread-synchronous locking, blocking queues, Synchronizer, using the thread pool's executor, execution framework, and thread-safe collections that can be used in multi-threading.

Multithreading Basics

The runnable interface and the thread class are the most basic ways to implement multithreading.

1. Create a thread

method One: encapsulate the code to be executed in the new thread in the run () method of the Runnable object, construct the thread object as a parameter of the Runable object, and invoke the Start () method of the Thread object. The parallel task starts executing in a new thread, and the current linear continuation executes the subsequent code until the end.

method Two: derive subclasses from THEAD, override the Run () method of the thread class, place the code in which to execute in the new thread, and then create the thread subclass object and call the start () method. This way you can save runnable wrapper classes, but create a subclass of thread.

It is recommended to use method one, because the method two thread object and the specific task one by one bound, to perform 1000 tasks will have to create an equal amount of threads, the cost is too high. The task should be separated from the thread object used to perform the task, which is encapsulated in the Runnbale object so that the thread pool can be used to perform a large number of tasks with a fixed number of threads.

You must call the start () method of the thread class to open a new thread. The run () method that directly calls the thread or Runnable object simply executes the task in the current thread.

Thread

      • thread (Runnable target) constructs thread,runnable objects with Runnable objects that are stored in the target domain of thread
      • void Run () by default if the target domain is not empty, execute target.run (), otherwise do nothing. You can inherit the thread class, override this method, put the code that you want to execute in the new thread, and no longer need the Runanble object to encapsulate the task code of the new thread.
      • synchronized void Start () creates a new thread and begins execution, and the JVM invokes the run () method of the thread object in the new thread. A thread object can only be called once and will return immediately, and two threads have already started executing in parallel after the call.
      • static Thread CurrentThread () returns the thread object of the threads (current thread) that are executing this command
      • void interrupt () sends an interrupt request to the thread, and the interrupt state of the thread is set to true. See the following article for special instructions.
      • boolean isinterrupted () tests whether the thread break state is set. The interrupt status is not changed.
      • The static Boolean isinterrupted () also tests whether the thread that is executing this command (the current thread) is set to break. The interrupt status is set to False after the call.

Runnable Interface wrapper content executed in a new thread

      • void Run () when a new thread is created, the code in the method is executed

Sample code

classMyThread extends Thread {Private intbegin;  Public voidSetcountstart (intBegin) { This. begin=begin;} @Override Public voidrun () {Try {                    intend=begin+ -;  for(intI=begin; i<end; i++) {System. out. println ("Sub:"+i); Thread.Sleep ( +); }                } Catch(interruptedexception e) {e.printstacktrace (); }}} MyThread t=NewMyThread (); T.setcountstart ( $);                T.start ();  for(intI=0; i< -; i++) {System. out. println ("Main:"+i); Thread.Sleep ( +); }
        classMyTask implements Runnable {Private intbegin=0;  PublicMyTask (ints) {begin=s;} @Override Public voidrun () {Try {                    intend=begin+ -;  for(intI=begin; i<end; i++) {System. out. println ("Sub:"+i); Thread.Sleep ( +); }                } Catch(interruptedexception e) {e.printstacktrace ();                }            }        }; Thread T=NewThread (NewMyTask (123));                T.start ();  for(intI=0; i< -; i++) {System. out. println ("Main:"+i); Thread.Sleep ( +); if(i==Ten) t.stop (); }
2. Terminating a thread

Auto End

The run () method of the thread or Runnable object wraps the code executed in the new thread, and the thread terminates automatically when the following condition is encountered in the run () method.

    • Execute last Statement
    • Encountered return returned
    • An uncaught exception occurred

Force end

    • Call the Stop () method of the thread object. Throws a Threaddeath exception (this exception is bound to be re-thrown if it is caught), stopping the thread from executing. This method is deprecated because the thread may stop in an insecure state and should use the way the request is interrupted.
    • request Interrupt Mode . To end a thread, set the interrupt variable for that thread (call the interrupt () method of the Thread object) (indicating that someone wants to break the thread), The code in the thread itself is responsible for querying the interrupt variable (the thread class static method interrupted () or the isinterrupted () method of the Thread object), and if it is found that the break variable is set, the conscious point should not be executed again, and then exit itself after returning to a safe state. The request interrupt is not mandatory , and if the code in the thread does not query the break variable, or if the break variable is found to have been set but ignores the continued cheeky execution, the thread will still run without being stopped.

void Interrupt () methods and interruptedexception special instructions

    • If this method is called when the thread is being blocked by some interruptible method (sleep,wait or interruptible io call, etc.), then it must be impossible to detect the interrupt state, clean the interrupt state , Immediately throws an Interruptedexception exception, and the blocked method call is immediately interrupted by this exception.
    • If this method is called to set the interrupt state to True, then an interruptible method (sleep,wait, interrupt io call, etc.) is called, and the call does not succeed, and the interrupt state is also cleared. Throws a Interruptedexception exception . It can be seen that if you iterate through the interruptible methods of Sleep (), you do not need to detect the interrupt state manually .

(Note that there are also blocking IO calls that cannot be interrupted, and it is best not to use an interruptible method).

As long as the interruptedexception is thrown, the interrupt state must have been cleared, this is only interruptedexception this exception is we know that there is an interrupt request is the only identity, we must notify the outer layer of an interrupt occurred, Do not suppress this exception, otherwise how to call the Interrupt () method request interrupt will not have any eggs, the thread of the foreign layer of the code is not aware of the interruption of this matter, as usual. There are two ways to notify the outer layer of this interrupt request:

    • When catch to Interruptedexception, call Thread.CurrentThread (). Interrupt (), re-set the interrupt state to allow the outer layer to be detected.
    • The best way to do this is to stop the catch interruptedexception exception and throw it to the outer layer as long as you have the exception. Always throws to the outermost layer, handling the exception in the thread object or the run () method of the Runnable object.

The direct call to the Stop () method is shown in the previous instance code. Examples of interrupt mode are as follows:

        classMyinterruptablechecktask implements Runnable {Private intbegin=0;  PublicMyinterruptablechecktask (ints) {begin=s;} @Override Public voidrun () {intEnd = begin +3000000;  for(inti = begin; I < end &&! Thread.CurrentThread (). isinterrupted (); i++) {System. out. println ("Sub:"+i); }                if(thread.currentthread (). isinterrupted ()) System. out. println ("Sub thread is interrupted"); ElseSystem. out. println ("Sub Natural Stop");                }        }; Thread T=NewThread (NewMyinterruptablechecktask (111));                T.start ();  for(intI=0; i<Ten; i++) {System. out. println ("Main:"+i); Thread.Sleep ( +); if(i==5) t.interrupt (); }
classMyinterruptableexceptiontask implements Runnable {Private intbegin=0;  PublicMyinterruptableexceptiontask (ints) {begin=s;} @Override Public voidrun () {Try {                    intend=begin+Ten;  for(intI=begin; i<end; i++) {System. out. println ("Sub:"+i); Thread.Sleep ( +  );//If the setting is interrupted when sleep is in progress, or if sleep is encountered in a loop after the interrupt is set, the Interruptedexception exception will be thrown, and no need to manually detect the interrupt state.                    }                } Catch(interruptedexception e) {System. out. println ("The call Thread.Sleep (n) are interrupted by Interruptedexcetpion");    Thread.CurrentThread (). interrupt (); //The interrupt state is cleared when the interruptedexception exception is generated, all the interrupts are reset or thrown out for subsequent code to detect if an interrupt has occurred                }                        if(thread.currentthread (). isinterrupted ()) System. out. println ("Sub thread is interrupted"); ElseSystem. out. println ("Sub Natural Stop");                }        }; Thread T=NewThread (NewMyinterruptableexceptiontask (111));                T.start ();  for(intI=0; i<Ten; i++) {System. out. println ("Main:"+i); Thread.Sleep ( +); if(i==5) t.interrupt (); }

3. Status of the thread

AWT Event Allocation thread

"Java Core technology Volume One" notes multithreading

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.