JAVAThread multi-thread Learning

Source: Internet
Author: User

JAVAThread multi-thread Learning

I learned java for the second time and found that many knowledge points were not understood before. In the java multi-Thread section, we learned not only to inherit the Thread to implement the runnable interface, but also the third Thread method based on the Thread pool to implement the callable interface. I feel that java is truly profound and profound. Summary of java thread notes:

A java thread is called a single-threaded program. A java program is called a multi-threaded program after multiple programs are executed.

1: Multithreading
(1) multithreading: an application has multiple execution paths. Process: The application thread being executed: The Execution Unit of the process. The execution path is single thread: one application has only one execution path and multiple threads: one application has multiple execution paths.

What is the significance of multi-process? What is the significance of improving CPU usage by multithreading? Improve Application Usage (2) How Java programs run and does JVM start multithreading? A: run the Java command to start JVM. JVM starts A process that starts A main thread. B: JVM startup is multi-threaded, because it has two threads at least, the main thread and the garbage collection thread.
(3) multi-Thread implementation solution A: Inheriting Thread class B: Implementing the Runnable interface
* Comparison of the two methods

(4) thread scheduling and priority problem A: Thread Scheduling
  • A: time-based scheduling
  • B: preemptive Scheduling (Java adopts this scheduling method)
  • B: Obtain and set the thread priority. a: The default value is 5. B: The value range is 1-10.
    (5) thread control (common method) A: Sleep thread API method:

    Thread sleep in milliseconds

    • Public static void sleep (long millis) B: Method for adding a thread API

      Join: Wait for the thread to terminate. Wait until the thread execution is complete before other threads can run.

      • Public final void join (); C: courtesy thread API method

        To some extent, the execution of multiple threads is harmonious and unreliable.

        • Public static void yield () D: backend thread API method
          • Public final void setDaemon (boolean on)
            When all running threads are daemon threads, the Java Virtual Machine exits. This method must be called before the thread starts.
            After being marked as a daemon thread, the thread will be attached to a thread and will not be independent of runE: Terminate the thread (master) API method
            • Public final void stop () causes the thread to stop, which is out of date

            • Public void interrupt () terminates the thread, throws an InterruptedException exception, and executes subsequent code.

              Thread Life Cycle (refer to the line Life Cycle Graph to extract .bmp)

              A: New

              Process of creating a thread object <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Vcd4kpg1_pki6vs3q9zwvadq + expires + jI + zwvaDQ + expires + zzLbUz/ox5lp1_ky7 + KOstci0/expires = "brush: java;"> (7) cinema ticket selling program implementation A: Inheriting Thread class B: Implementing the Runnable interface (8) cinema ticket selling program problems A: adds sleep for 100 milliseconds to better suit real scenarios. B: Ticket Selling problem a: Same ticket multiple times B: Negative ticket (9) the cause of the multi-thread security problem (which is also the basis for us to determine whether A program has a thread security problem in the future): multi-threaded environment B: Shared data C: Multi-statement operations shared data(10) Synchronization solves thread security issues A: Synchronous Code Block

              Synchronized (object ){
              Code to be synchronized;
              }

              The lock object can be any object.

              B: Synchronization Method

              Add synchronization to the method.

              The lock object here is this

              C: static Synchronization Method

              Add synchronization to the method.

              The lock object here is the object of the byte code file of the current class (the object of the byte code file will be reflected again)

              (11) review previous thread-safe classes
              • A: StringBuffer
              • B: Vector
              • C: Hashtable
              • D: How to change a collection class with unsafe threads into a collection class with thread-safe methods using the Collections tool class.
              Related Knowledge points (1) Lock operations and release operations for threads after jdk5.
              // Define the Lock Object private lock = new ReentrantLock (); @ Override public void run () {while (true) {try {// Lock. lock (); if (tickets> 0) {try {Thread. sleep (100);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println (Thread. currentThread (). getName () + "selling" + (tickets --) + "tickets") ;}} finally {// release lock. unlock ();}}}
              (2) Description and code embodiment of the deadlock problem
              • Two or more threads are waiting for each other for resources during execution.
              • Nested cases of Synchronous Code Blocks
              @ Overridepublic void run () {// deadlock code if (flag) {// synchronize nested synchronized (MyLock. objA) {System. out. println ("if obja"); synchronized (MyLock. objB) {System. out. println ("if objb") ;}} else {synchronized (MyLock. objB) {System. out. println ("else objb"); synchronized (MyLock. objA) {System. out. println ("else obja ");}}}}
              (3) multi-thread representation of producers and consumers (Inter-thread communication issues)
              Resource class implemented by students as resources: Student sets data class: SetThread (producer) obtains data class: GetThread (consumer) test class: StudentDemo code: A: the most basic version, only one data. B: improved versions, different data are provided, and the synchronization mechanism is added. C: wait for the wake-up mechanism to improve the program, so that the data can appear in sequence. wait () the lock held by the thread is released immediately after the thread waits, and the waiting position continues to execute notify () Wake-up does not mean that the thread can be immediately executed into the ready state and waits for the next execution of notifyAll () (Multi-production and multi-consumption)
              • Why is it defined in Object?
                • These methods are called through lock objects, and the locks we use may be arbitrary lock objects. Therefore, these methods must be defined in the Object class = * code optimization waiting for the wake-up mechanism. Write Data and operations in the resource class (4) thread group
                  • ThreadGroup is used in Java to represent a thread group. It can manage a batch of threads by category. Java allows programs to directly control the thread group. By default, all threads belong to the main thread group ).
                    Returns the thread group to which the thread belongs.
                  • Public final ThreadGroup getThreadGroup ()
                    We can also set groups for threads.
                  • Thread (ThreadGroupgroup, Runnabletarget, Stringname)
                    Code for creating a thread group:

                    // ThreadGroup (String name) ThreadGroup tg = new ThreadGroup ("this is a new group"); MyRunnable my = new MyRunnable (); // Thread (ThreadGroup group, Runnable target, string name) Thread t1 = new Thread (tg, my, "Lin Qingxia"); Thread t2 = new Thread (tg, my, "Liu Yi"); System. out. println (t1.getThreadGroup (). getName (); System. out. println (t2.getThreadGroup (). getName (); // sets the background thread by group name, indicating that all threads in this group are background thread tg. setDaemon (true );
                    (5) thread pool

                    It is relatively high for a program to start a new thread because it involves interacting with the operating system. The use of the thread pool can improve performance, especially when the program needs to create a large number of threads with short lifetime, we should consider using the thread pool.

                    • After the code of each thread in the thread pool ends, it will not die, but return to the thread pool again to become idle and wait for the next object to use.
                    • Before JDK 5, we must manually implement our own thread pool. From JDK 5, Java has built-in support for thread pools.
                    • JDK 5 adds an Executors factory class to generate a thread pool. The following methods are available:

                      Public static ExecutorService newCachedThreadPool ()

                      Create a thread pool cache with cache function: reaccess to Baidu browsed Information

                      Public static ExecutorService newFixedThreadPool (int nThreads)

                      Create a reusable thread pool with a fixed number of threads

                      Public static ExecutorService newSingleThreadExecutor ()

                      Create a thread pool with only one thread, which is equivalent to the parameter 1 of the previous method.

                      Protected void shutdown ()
                      The return value of these methods in the thread pool is the ExecutorService object. This object indicates a thread pool and can execute Runnable objects or the threads represented by Callable objects. It provides the following methods:
                      Future Submit (Runnable task)
                      Futuresubmit (Callabletask)

                      (6) The third solution for Multithreading

                      The steps for implementing the Callable interface are similar to those for executing the Runnable object in the demo thread pool. But it can be more fun. The benefit of the summation case is that the return value can throw an exception. disadvantage: the code is complicated, so it is generally not used.

                      Use multithreading for anonymous internal classes

                      New Thread () {Code ...}. Start (); New Thread (new Runnable () {Code ...}). Start ();

                      The usage of the multi-threaded application timer is described as follows:
                      • A timer is a widely used thread tool. It can be used to schedule multiple scheduled tasks and run them in subsequent threads. In Java, the Timer and TimerTask classes can be used to define scheduling.

                      • A tool used by a thread to schedule tasks to be executed in a background thread. You can schedule the task to be executed once, or perform the task repeatedly on a regular basis.

                        Public Timer ()
                        Public void schedule (TimerTasktask, longdelay)
                        Public void schedule (TimerTask task, long delay, long period)
                        * The TimerTask task class is used to specify the public abstract void run () task for Timer ()
                        Public boolean cancel ()
                        * Under development
                        Quartz is an open-source scheduling framework fully written by java.

                        Thread life cycle conversion diagram:


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.