20165306 Eighth week learning tasks

Week 8 study assignments

Textbook learning content summary

12.1 Processes and threads

1. Operating system and process

  • 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.
  • Multiple processes in a computer system can use CPU resources in turn, and even multiple processes can share resources managed by the operating system.

2. Processes and threads

  • A thread is not a process, but a smaller execution unit than a process. Interruption and recovery of threads can save system overhead.
  • There can be no threads without processes, and no processes without an operating system.

12.2 Threads in Java

1. Java's multi-threading mechanism

  • 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. These threads are executed in turn, giving each thread a chance to use CPU resources.

2. Main thread (main thread)

The main thread (main thread) is responsible for executing the main method.

3. Thread state and life cycle

Threads are represented using objects of the Thread class and its subclasses.

  • 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. The program must rewrite the run() method of the parent class in the subclass. Before the thread ends the run() method, do not let the thread call the start() method again, 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. One of the causes of death is to finish executing all the statements in the run() method, ending the run() method; the second cause of death is to force the end of the run() method.

Example 12_1

In this example, two threads are created with subclasses of Thread in the main thread. These two threads output 20 sentences of "elephant" and "car" respectively in the command line window, and the main thread outputs 15 sentences of "master" in the command line window. .

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 of the thread can be returned by the getPriority``` method.

  • 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.

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.

2. Use the Thread class

  • New member variables and methods can be added to subclasses. Java does not support multiple inheritance, and subclasses of the Thread class cannot extend other classes.

  • Use the Thread class to directly create a thread object: ```` Thread(Runnable target), the parameter in the constructor is an interface of the Runnable type.

  • 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.

Example 12_2

Instead of using a subclass of the Thread class to create threads, use the Thread class to create speakElephant and speakCar threads.

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.

String name=Thread.currentThread().getName();

Example 12_3

  • The target object combines threads (weak coupling): The target object can determine which thread is being executed by the JVM by obtaining a reference to the thread object.

Thread.currentThread();

Example 12_4

12.4 Common Methods of Threads

  • isAlive()

    • When the thread is in the new state, the thread calls the isAlive() method and returns false
    • Returns true before entering the dead state
    • After entering the dead state (the entity memory is released), return false

Note: When an already running thread does not enter the dead state, do not allocate entities to the thread. Since the thread can only refer to the last allocated entity, the previous entity will become "garbage" and will not be collected by the garbage collector. .

Example 12_5

  • currentThread(): Can be called with a class name, this method returns the thread that is currently using CPU resources.

  • interrupt(): Wake up the dormant thread, that is, cause the dormant thread to have an InterruptedException exception, thereby ending the dormancy and re-queuing for CPU resources.

Example 12_6

12.5 Thread synchronization

Multiple threads calling the synchronized method must obey the synchronization mechanism.

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

Example 12_7

12.6 Coordinating Synchronized Threads

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

Example 12_8

Problems and Solving Processes in Teaching Materials Learning

"P373 When two or more threads access the same variable at the same time, and some threads need to modify this variable. The program should handle such problems, otherwise confusion may occur."

Problems and solutions in code debugging

  • Problem: The compilation failed, but the operation was successful, as shown below:

  • Answer: Write less joinThread.join()(the current thread starts to wait for the end of joinThread) this line of code

code hosting

Summary of last week's exam mistakes

  • The DriverManager manages a set of basic services for JDBC drivers. New in the JDBC 2.0 API, the DataSource interface provides another way to connect to a data source. Using a DataSource object is the preferred method of connecting to a data source.

  • Option D is wrong, JDBC provides APIs for Java programmers, database vendors and third-party middleware vendors.

learning progress bar

Lines of code (added/accumulated) Blog volume (new/cumulative) Study time (added/accumulated)
Target 5000 lines 30 articles 400 hours
eighth week 1463/5276 2/13 8/91

Guess you like

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