Java Multithreaded Learning

Source: Internet
Author: User

First, how to achieve multi-threading
    • Implementing the Runnable Interface
1  Public Static voidMain (string[] args) {2MyThread MyThread =NewMyThread ();//A class that implements the Runnable interface3Thread T =NewThread (MyThread);//Declaration of a thread4T.start ();//Start thread5}6 7  Public classMyThreadImplementsRunnable {8@Override9      Public voidRun () {//method to execute after starting threadTenSystem.out.print ("run the \ "run () \" method!"); One} A}
    • Inherit the Thread class
1  Public Static voidMain (string[] args) {2MyThread MyThread =NewMyThread ();//A class that inherits the thread class3Mythread.start ();//Start thread4}5 6  Public class extendsThread {7@Override8      Public voidRun () {//method to execute after starting thread9System.out.print ("run the \ "run () \" method!");Ten} One}
    • Create a thread with a return value using Executorservice, future, and callable
1  Public Static voidMain (string[] args) {2     //Create a Executorservice3Executorservice Executorservice =4Executors.newcachedthreadpool ();5     //New one mythread thread, and handed to Executorservice to execute,6     //Receive return results via future7Future future =8Executorservice.submit (NewMyThread ());9     Try{Ten         //Get the return value from the future OneObject result = Future.get (); ASystem.out.println (Result.tostring ()); -}Catch(Exception e) { -E.printstacktrace (); the} -} -  - //A thread that has a return value +  Public classMyThreadImplementsCallable { -@Override +      PublicString Call () { ASystem.out.print ("run the \ "call () \" method!"); at         return"Test"; -} -}
Second, the substance


  1 Runnable, callable interface and multi-threaded implementation is not related to the role of the   2 interface is constrained behavior, the role of Runnable interface is to specify a protocol, All classes that inherit these interfaces are required to have a method with no parameter and no return value.   3 A multi-threaded implementation is a   4-native method that is done by a class and is not implemented in the Java language.
      • There are two ways to define the work to be done in multi-threading
        • Implementing the Runnable Interface
          The run () method in the Runnable interface does not return a value
        • Implementing the Callable Interface
          The call () method in the callable interface has a return value
        1. Threads need to be managed (commit, start, terminate)
          1. Thread class
            • The Thread class has a constructor that can pass a Runnable type of parameter target, which can be used to submit the desired task (implementing the Run () method and passing it to the thread instance)
            • The thread class itself implements the Runnable interface, or you can submit the task you want to perform directly by implementing the thread class (overriding the Run () method)
            • The start () method of the thread class is responsible for starting the execution thread when the start () method executes
              • If the run () method has been rewritten to perform the task, the method is executed
              • If the target parameter is passed in, the Run () method in target is called
            • There is a stop method in the thread class that is responsible for stopping the thread, but it has been deprecated
            • The thread can be broken through the interrupt () method
          2. Executorservice interface
            • Tasks can be submitted through the executor () method or the Submit () method
            • The task submitted by the submit () method returns a future object that can be used to retrieve the returned result
            • The shutdown () and Shutdownnow () methods can be used to stop the thread pool
      Third, detailed
        • thread life cycle
        • new Thread (new): Creates a thread instance, such as creating an instance of the thread class with the new operation, when the thread is not started
        • runnable ( Operational): After a thread is created, it is necessary to notify the CPU that the thread can start executing, such as the start () method of the thread class executes, at which point the thread waits for the CPU to allocate resources in the ready queue
        • running (running): Thread gets CPU After the source runs, such as running the logic in the Run () method, unless the thread automatically discards the CPU resources or a higher priority thread enters, it executes to the end of the thread
        • Dead (death): The thread is executed at the end of the normal execution, or is killed, and the thread will not be Execute
        • block (block): Thread actively let go of the CPU, other higher priority thread, the thread's time slice run out, but at this time the thread has not completed, will bring the thread into the block state, the thread into the block state can also go back to the ready queue waiting Execute again.
        • Methods in the Thread class
          • Start: Start a thread, this method will be the thread into the Runnable state, waiting for execution
          • IsAlive: Determines whether the thread is active (Runnable or running)
          • Sleep: Forces the thread to discard the current time slice into hibernation for a certain amount of time, when the thread enters the block state until the time of hibernation ends and then enters the Runnable state. Sleep is a static method that only controls the thread. Sleep (0) directly triggers the next CPU race, and if there are no higher priority threads, it will continue to work
          • Wait (Override object): Discards the lock, enters the wait pool, and then enters the Runnable state again only after the Notify () method is called for this object
          • Join: Blocking waits for threads to end, can receive parameters Millis and Nanos Specify the maximum time to wait
          • Interrupt: In the thread, this method does not interrupt the running threads, after running the method, only if the thread is blocked by join (), sleep () and Wait () method, will be interrupted by the interrupted method, and throw a interrupted Exception exception
          • Static yield: The active abandonment of CPU use, back to Runnable state
        Four, Tips
          1. block State
            1. waits for blocking: The running thread executes the wait method, which frees all resources that are consumed, including object locks, into the wait queue. Threads that enter the queue are not automatically awakened, and must rely on other threads to invoke notify (), Notifyall () to wake up (the state thread will release the object lock)
            2. synchronous blocking: When the running threads acquire an object synchronization lock, the synchronization lock is occupied by another thread. The thread enters the lock queue to wait for a sync lock until it gets to the synchronization lock and then back into the Runnable state (the state thread has not yet acquired the object lock)
            3. Other blocking: The running threads call the sleep () or join () method, or make an IO request, the The thread goes into a blocking state, knowing that the sleep timeout, the end of the thread that the join is waiting for, or the IO operation is complete, and then goes into the Runnable state again (the status offline will discard the CPU without releasing the object lock)
          2. sleep (0
            Sleep (0) will re-trigger the CPU contention, and when there are threads greater than or equal to the current thread priority in the Runable queue, the current thread will go into the Runnable queue to give up the use of the CPU, otherwise it will continue to run
          3. sleep () and The wait ()
            • Sleep method yields the CPU, but does not release the object lock until the sleep timeout is automatically entered into the Runnable queue
            • The wait method yields the CPU and releases the object lock, requiring other threads to tune Use Notify (), Notifyall () to re-enter the Runnable queue
          4. interrupt ()
            Interrupt method is more inclined to tell the thread that you can end it instead of directly interrupting the line Thread into the blocking state before it is disconnected. For threads that are trapped in a dead loop, IO wait, and so on, the interrupt method cannot be effectively interrupted.
          5. sleep () and yield ()
            Both methods will let the CPU use, sleep will enter the block state, and yield will go directly into the Runnable state


        This article originates from: hacpai:zl992532172

        Java Multithreaded Learning

        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.