20165318 2017-2018-2 "Java Programming" Eighth Week Learning Summary

20165318 2017-2018-2 "Java Programming" Eighth Week Learning Summary

content

Problems encountered in the learning process and summary

  • Q1 : When running the textbook code 12_1, the results are as follows: the results are not the same as those in the textbook. After running it again, it is found that the results are not the same as the last time.

  • Solution process : After reading the book carefully, I found that the book explained, "The results of the program running on different computers or running repeatedly on the same computer are not the same, and the output results depend on the current CPU resource usage."

  • Q2 : In this week's class quiz, when I was writing "Calculate the longest and shortest living countries", the country with the longest lifespan in the output was correct, but the country with the shortest lifespan was consistently wrong:

  • Resolution process : After repeated corrections, I found the following errors:
    • The country whose lifespan record is empty, that is, the lifespan is 0, is not removed;
    • Putting the longest and shortest countries in two loops results in the bottom end of the database being read when calculating the longest-lived countries.
    • Assigning agemin to 0 results in no country in the database with a lifespan less than 0, and assigning agemax to 100, no country with a lifespan greater than 100 is found.
      The following is the correct result:

Back to Contents

Textbook learning content summary

Chapter 12 Java Multithreading Mechanisms

12.1 Processes and Processes

  • A program is a piece of static code, a process is a dynamic execution process of a program, and this process is also the process of the process itself from birth, development to death.

  • A thread is not a process, it is a smaller unit of execution than a process. But unlike the process, the interruption and recovery of the thread can save the system overhead.

  • There are no threads without processes.

12.2 Threads in Java

1. Java's multi-threading mechanism
  • A major feature of the Java language is its built-in support for multithreading.

  • Multi-threading refers to the situation that several execution books exist in an application at the same time, and work together according to several different execution threads.

  • A 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, the main thread (main thread)
  • The main thread (main thread) is responsible for executing the main method.

  • If no other threads are created in the main method, then when the main method finishes executing the last statement, that is, when the main method returns, the JVM will end the Java application. If other threads are created in the main method, then the JVM will switch between the main thread and other threads in turn to ensure that each thread has the opportunity to use the CPU, even if the main method finishes executing the last statement (the main thread ends), The JVM also does not end the Java application. The JVM waits until all the Java applications are finished before ending the Java application.

3. Thread status and life cycle

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

A newly created thread usually goes through the following four states in a complete life cycle:

  • New: An object of the Thread class or its subclasses is declared and created, and it already has the corresponding memory space and other resources.

  • Running: When the JVM switches the CPU usage right 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 is executed immediately, and the program must override the run() method of the parent class in the subclass.
    Do not let the thread call the start() method again before the thread ends the run() method, otherwise an IllegalThreadStateException will occur.

  • Interruptions: There are four reasons for interruptions
    • The JVM switches the CPU resources from the current thread to other threads, so that the thread gives up the right to use the CPU and is in an interrupted state.
    • While the thread is using CPU resources, the sleep(int millsecond) method is executed to make the current thread go to sleep.
    • After the wait() method is executed, the current thread enters the waiting state, and other threads must call the notify() method to notify it, so that it re-enters the thread queue to queue for CPU resources.
    • Performing an operation to enter the blocking state, such as performing a read/write operation causes blocking. Only when the cause of the blocking is eliminated, the thread re-enters the thread queue to queue for CPU resources.
  • Death: Does not have the ability to continue running. The essence is that the thread releases the entity, that is, releases the memory allocated to the thread object.
    • One of the causes of death is that all the statements in the run() method are executed, ending the run() method;
    • The second cause of death is forcing the run() method to end.
4. Thread scheduling and priority
  • Each Java thread has a priority between the constants 1 and 10, i.e. Thread.MIN_PRIORITYand Thread.MAX_PRIORITY. If the thread's priority level is not explicitly set, each thread has a constant priority of 5, ie Thread.NORM_PRIORITY.

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

  • When the time for the thread to use the CPU resources expires, even if the thread has not completed all its own operations, the JVM will interrupt the execution of the current thread and switch the CPU usage right to the next queued thread, and the current thread will wait for the CPU resource. On the next round, then resume execution from where it left off.

  • The task of the JVM's thread scheduler is to enable high-priority threads to run all the time. Once the time slice is free, threads with the same priority will use the time slice in turn.

12.3 Thread class and thread creation

1. Use a subclass of Thread
  • When writing a subclass of the Thread class, you need to override the run() method of the parent class.

  • Advantages : You can add new member variables in the subclass to realize that the city has a certain attribute, or you can add a new method in the subclass to make the thread have a certain function.

  • Java does not support multiple inheritance, and subclasses of the Thread class cannot extend other classes.

2. Use the Thread class.
  • Create a thread object directly with the Thread class: Thread(Runnable target), the parameter in the constructor is an interface of the Runnable type.
    When creating a thread object, an instance of a class that implements the Runnable interface must be passed to the parameter of the constructor. The instance object is called the target object of the created thread. After the thread calls the start() method, once it is its turn to enjoy the CPU resources, The target object will automatically call the run() method in the interface (interface callback)

  • For threads using the same target object, the member variables of the target object are naturally the data units shared by these threads. Using the Runnable interface is more flexible than using a subclass of Thread.

3. The relationship between the target object and the thread
  • The target object and the thread are completely decoupled : the target object often needs to obtain the thread name (since there is no way to obtain a reference to the thread object) in order to determine which thread is being executed by the JVM.

  • The target object combines threads (weak coupling) : The target object can combine threads. When the target object class combines thread objects, the target object can obtain a reference to the thread object through.

4. About the number of times the run method is started
  • For threads with the same target object, when one of the threads enjoys the CPU resources, the target object automatically calls the run method in the interface. At this time, the local variables in the run method are allocated memory space, and when it is the turn of the other thread to enjoy the CPU resources , the target object will call the run method in the interface again, and the local variables in the run() method will allocate memory space again. That is, the run() method has been started and run twice, running in different threads.

12.4 Common Methods of Threads

  • start(): When the thread calls this method, it will start the thread and enter the ready queue from the newly created state. Once it is its turn to enjoy the CPU resources, it can start its own life cycle independently of the thread that created it.

  • run(): The function and function of the run() method of the Thread class is the same as that of the run() method in the Runnable interface. They are both used to define the operations performed after the thread object is scheduled. They are all methods that are automatically invoked by the system and cannot be referenced by user programs.

  • sleep(int millsecond): A thread with high priority can call the sleep method in its run() method to make itself give up CPU resources and sleep for a period of time.

  • isAlive(): When the thread is in the "New" state, the thread calls the isAlive() method and returns false. Before the thread's run() method ends, that is, before it enters the dead state, the thread calls the isAlive() method to return true.

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

  • interrupt():
    A thread that occupies CPU resources can let the sleeping thread call the interrupt() method to "wake up" itself, that is, cause the sleeping thread to have an InterruptedException exception, thereby ending the sleep and re-queuing for CPU resources.

12.5 Thread synchronization

  • Multiple threads calling a synchronizedmethod must obey the synchronization mechanism.

  • When dealing with thread synchronization, the first thing to do is to decorate methods that modify data with keywords synchronized.

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

  • Thread synchronization mechanism: When a thread A uses the synchronized method, other threads must wait until thread A finishes using the synchronized method.

12.6 Coordinating Synchronized Threads

  • wait()The method can interrupt the execution of the method, make the thread wait, temporarily give up the right to use the CPU, and allow other threads to use the synchronization method.

  • notifyAll()The method notifies all threads that are waiting due to the use of this synchronized method to end waiting. The thread that has been interrupted will continue to execute this synchronization method from the point where it was interrupted just now, and follow the principle of "interrupt first, continue first".

  • notify()The method just notifies one of the waiting threads that one of them has finished waiting.

  • wait(), notify(), notifyAll()are final methods in the Object class, which are inherited by all classes and are not allowed to be overridden. wait()You cannot use , notify(), , in an unsynchronized method notifyAll().

12.7 Thread unions

  • When a thread A occupies CPU resources, it can let other threads call join() to join with this thread, for example,
    B.join();
    A joins B during operation. If thread A joins thread B while it occupies CPU resources, thread A will immediately interrupt execution until the thread B it joins with is executed, and thread A will re-queue for CPU resources in order to resume execution. B.join() will have no effect if the B thread that A is preparing to join has ended.

12.8 GUI thread


  • When a Java program contains a graphical user interface (GUI), the Java virtual machine automatically starts more threads while running the application

  • two important threads
    • AWT-EventQuecue: Responsible for handling GUI events
    • AWT-Windows: responsible for drawing the form or component to the desktop

12.9 Timer threads

  • Use the methods of the Timer class to start()start the timer, that is, start the thread.

  • Use the methods of the Timer class to stop()stop the timer, that is, to suspend the thread.

  • Use restart()the restart timer, i.e. resume the thread.

  • Use to Timer(int a,Object b)create a timer that "rings" every a millisecond, and parameter b is the timer's monitor. The bell event that occurs on the timer is an ActinEvent type event. When the ringing event occurs, the monitor will monitor the event, and the monitor will call back ActionListenerthe method in the interface actionPerformed(ActionEvent e).

  • Note: The timer's monitor must be an instance of a subclass of the component class (eg JFrame, , JButtonetc.), otherwise the timer cannot start.

12.10 Daemon threads

  • Threads are non-daemon threads by default (ie, user threads).

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

  • When all user threads in the program have finished running, even if there are still statements to be executed in the run method of the daemon thread, the daemon thread will end running immediately.

  • The difference between user threads and daemon threads is the departure of the virtual machine. If all user threads have exited, and only the daemon threads remain, the virtual machine will exit.

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

Back to Contents

code hosting

Code cloud link

Code Statistics

Back to Contents

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324675855&siteId=291194637