20165318 2017-2018-2 "Java Programming" Eighth Week study summary

Source: Internet
Author: User
Tags switches thread class hosting

20165318 2017-2018-2 "Java Programming" Eighth Week study summary

Directory
    • Problems encountered in learning process and summary
    • Summary of learning contents of textbook
      • The 12th Chapter Java multithreading mechanism
    • Code Hosting
    • Code statistics

Problems encountered in learning process and summary
    • Q1: When running the textbook code 12_1, the results are as follows: not the same as the results of the textbook, and then run it again, and the result is not the same as the last time.

    • resolution process : After reading carefully, the book explains that "the program runs on different computers or runs repeatedly on the same computer, and the output depends on the current CPU resource usage."

    • Q2: In this week's class test, when I wrote "Longest and shortest country", the country with the longest lifetime in the output was right, but the country with the shortest life had been wrong:

    • resolution process : After repeated correction, I found in the following several errors:
      • No removal of the life record as empty, i.e. a country with a lifespan of 0;
      • Countries with the longest life expectancy and the shortest life span have been placed in two cycles, leading to a reading of the bottom of the database in countries with the longest lifetime of computing.
      • Assigning a value of Agemin to 0, resulting in a database of no longer than 0 in the life of the country, the Agemax is assigned to 100, there is no discovery life than 100 countries.
        The following are the correct results:

Back to Catalog

Summary of learning contents of textbook

12th Java Multithreading Mechanism 12.1 process and process
    • A program is a static code, the process is a process of dynamic execution of a program, which is the process itself from the generation, development to extinction process.

    • A thread is not a process, it is a smaller execution unit than a process. However, unlike the process, threading interrupts and restores can be more cost-efficient for the system.

    • There is no thread without a process.

Thread 1 in 12.2Java, multithreading mechanism for Java
    • A major feature of the Java language is the built-in support for multithreading.

    • Multithreading refers to a situation in which there are several executions in an application that work together according to several different execution threads.

    • The computer can only execute one of the threads at any given time. The Java Virtual machine quickly switches control from one thread to another, and these threads are executed in turn, giving each thread a chance to use CPU resources.

2. Main threads (main thread)
    • The main thread (main threads) is responsible for executing the main method.

    • If no other thread is created in the main method, the JVM ends the Java application when the main method finishes executing the last statement, that is, when the main method returns. If another thread is created in the main method, the JVM will switch between the main thread and the other threads, ensuring that each thread has the opportunity to use the Cpu,main method even after the final statement is executed (the main thread ends), the JVM does not end the Java application. The JVM has to wait until the Java application has finished before ending the Java application.

3. The State and life cycle of the thread

The Java language uses objects of the thread class and its subclasses to represent threads.

The newly created thread typically undergoes the following 4 states in a full life cycle:

    • NEW: An object of the thread class or its subclasses is declared and created, and the corresponding memory space and other resources are already available.

    • Run: When the JVM switches the CPU usage to the thread, the thread can start its own life cycle independently of the main thread that created it.
      If the thread is created by a subclass of thread, the run () method in the class executes immediately, and the program must override the parent class's run () method in the subclass.
      Do not let the thread call the start () method again until the threads have finished the run () method, or the illegalthreadstateexception exception will occur.

    • Interrupts: Interrupts for four different reasons
      • The JVM switches the CPU resources from the current thread to other threads, leaving the thread out of the CPU's right to use the interrupt state.
      • During thread usage of CPU resources, the sleep (int millsecond) method is executed to put the current thread into hibernation.
      • Executes the wait () method, which causes the current thread to enter a wait state, which must be notified by other threads calling the Notify () method, so that it is re-queued to the thread queue to wait for CPU resources.
      • Performing an operation into a blocking state, such as performing a read/write operation, causes blocking. Only if the cause of the blocking is eliminated, the thread is re-entered into the thread queue waiting for CPU resources to be queued.
    • Death: Does not have the ability to continue running. The essence is that the thread frees the entity, which frees the memory allocated to the thread object.
      • One of the causes of death is to end the run () method by executing all the statements in the run () method;
      • The second cause of death is the forced run () method to end.
4. Thread scheduling and Priority
    • Each Java thread has a priority between constants 1 and 10, that is, Thread.MIN_PRIORITY and Thread.MAX_PRIORITY between. If the priority level of the thread is not explicitly set, the priority for each thread is constant 5, that is Thread.NORM_PRIORITY .

    • setPriority(int grade)the priority can be adjusted by method, and getPriority the method returns the priority of the thread.

    • When the thread uses the CPU resource time, even if the thread does not complete its own operation, the JVM interrupts the execution of the current thread, switches the CPU's use to the next queued thread, and the current thread waits for the next cycle of CPU resources and then resumes execution from the middle.

    • The task of the JVM's thread scheduler is to enable high-priority threads to always run, and once the time slices are idle, the threads with the same priority will use the time slices in a rotating fashion.

12.3Thread class and thread creation 1, subclasses using thread
    • When you write a subclass of the thread class, you need to override the run () method of the parent class.

    • Pros : You can add new member variables to a subclass, implement the city with some kind of attribute, or add new methods to the subclass to make the thread have some kind of function.

    • Java does not support multiple inheritance, and subclasses of the thread class can no longer extend other classes.

2, use the thread class.
    • Create a thread object directly with the thread class: the Thread(Runnable target) parameter in the constructor method is an interface of type runnable.
      When you create a thread object, you must pass an instance of the constructed method's parameters to the constructor of the Runnable interface class, which is called the target object of the created thread, and when the thread calls the start () method, the target object automatically calls the run () in the interface once it has its turn to enjoy the CPU resources. Method (interface Callback)

    • For threads that use the same target object, the member variables of the target object are naturally the data units shared by those threads, and using the Runnable interface is more flexible than subclasses using thread.

3. The relationship between the target object and the thread
    • The target object and thread are fully decoupled : The target object is often required to determine which thread is being executed by the JVM by acquiring the name of the thread (because a reference to the thread object cannot be obtained).

    • target object combination thread (weakly coupled): The target object can be combined with threads, and the target object class can combine thread objects when the target object is able to obtain a reference to the thread object.

4, about the number of times the Run method started
    • For a thread with the same target object, when one of the threads is enjoying CPU resources, the target object automatically calls the Run method in the interface, where the local variable in the Run method is allocated memory space, and when the other thread is on the CPU resource, the target object calls the Run method in the interface again, run ( ) The local variable in the method allocates memory space again. The run () method has started running two times, running in separate threads
Common methods for 12.4 threads
    • start(): The thread calls the method to start the thread and queue it from the new state into the ready queue, and once it comes to the CPU resource, it can start its own life cycle independently of the thread that created it.

    • run(): The Run () method of the thread class is the same as the function and function of the run () method in the Runnable interface, and is used to define the operations that are performed after the thread object is dispatched, which are methods that the system automatically calls and that the user program must not refer to.

    • sleep(int millsecond): A high-priority thread can call the sleep method in its run () method to allow itself to abandon CPU resources and hibernate for a period of time.

    • isAlive(): The thread calls the IsAlive () method to return False when the thread is in the new state. The thread calls the IsAlive () method to return True before the run () method of the threads ends, that is, before the death state is entered.

    • currentThread():
      The method is a class method in the thread class and can be called with the class name, which returns the thread that is currently using the CPU resource.

    • interrupt():
      A thread that occupies a CPU resource can let the dormant thread invoke the interrupt () method to "wake up" itself, that is, the thread that caused the sleep interruptedexception an exception, thus ending hibernation and waiting for CPU resources to be queued again.

12.5 Thread Synchronization
    • Multiple thread invocation synchronized methods must adhere to the synchronization mechanism.

    • The first thing to do when dealing with thread synchronization is to modify the method of the data with keywords synchronized .

    • The so-called thread synchronization is a method that several threads need to use a synchronized adornment.

    • Thread synchronization mechanism: When a thread A uses the Synchronized method, other threads must wait until thread a uses the synchronized method when they want to use the Synchronized method.

12.6 Coordinating Threads for synchronization
    • wait()Method interrupts the execution of the method, causes the thread to wait, temporarily yields the CPU, and allows other threads to use the synchronization method.

    • notifyAll()Method notifies all the waiting threads that are waiting by using this synchronization method. The thread that was interrupted will continue to execute this synchronization method from the point where it was just interrupted, and follow the principle of "first break first".

    • notify()Method simply notifies the waiting thread of the end of a wait.

    • wait(),, are the notify() notifyAll() final methods in the object class, are inherited by all classes, and do not allow the method to be overridden. cannot be used in a non-synchronous wait() method notify() , notifyAll() .

12.7 Thread Federation
    • While a thread A is occupying CPU resources, it is possible for other threads to call join () and this thread union, such as:
      B.join();
      Called a during the run Union B. If thread A is federating a B thread during the time it occupies CPU resources, the A thread will immediately break execution until it has finished executing the thread B of its union, and a thread then re-queued for CPU resources to resume execution. If a ready-to-federate B-thread has ended, then B.join () will have no effect.
12.8GUI Threads
    • When a Java program contains a graphical user interface (GUI), the Java Virtual machine runs the application automatically
      To start more threads

    • Two important threads
      • AWT-EventQuecue: Responsible for handling GUI events
      • AWT-Windows: Responsible for drawing a form or component to the desktop
12.9 Timer Thread
    • Use the Timer class method start() to start the timer, that is, to start the thread.

    • Use the Timer class's method stop() to stop the timer, which is to suspend the thread.

    • Use restart() the restart Timer, which is the recovery thread.

    • Using the Timer(int a,Object b) Create a timer, the timer "rings" once every a millisecond, and parameter B is the monitor of the timer. The Bell event that occurs in a timer is a actinevent type event. When a ringing event occurs, the monitor monitors the event and the monitor backs up the ActionListener method in the interface actionPerformed(ActionEvent e) .

    • Note: the watchdog of the timer must be an instance of the subclass of the component class (for example JFrame , JButton etc.), otherwise the timer cannot start.

12.10 Daemon Threads
    • A thread defaults to a non-daemon thread (that is, a user thread).

    • A thread invocation void setDaemon(boolean on) method can set itself as a daemon (Daemon) thread, for example:thread.setDaemon(true);

    • When all user threads in the program have finished running, the daemon thread ends immediately, even if there are statements in the daemon's run method that need to be executed.

    • The difference between a user thread and a daemon thread is the departure of the virtual machine. If the user thread is all out of operation and only the daemon thread is present, then the virtual machine exits.

    • A thread must set itself before running whether it is a daemon thread.

Back to Catalog

Code Hosting

Code Cloud Link

Code statistics

Back to Catalog

20165318 2017-2018-2 "Java Programming" Eighth Week study summary

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.