20165333 Eighth week study summary

Textbook learning content summary

Chapter 12 Java Multithreading Mechanism

A process can spawn multiple threads during its execution. A thread is a smaller execution unit than a process. The
JVM guarantees that each thread has a chance to use CPU resources and waits until all threads in a Java application are finished before ending the application.
Thread state and life cycle

Use the object of the Thread class and its subclasses to represent the thread
. Call the start() method to add the thread to the JVM management queue. After the call, the thread can no longer call the start() method
and the run() method specifies the specific mission of the thread. The thread becomes dead after the method is executed.
-sleep(int millsecond) puts the thread to sleep. A thread with a high priority can give up CPU resources, and a thread with a low priority executes the
wait() method to make the thread enter the waiting state. Continue the thread from where it left off by using the notify() method. The wait() method is usually placed in a "while" loop statement

  • Common method

isAlive() is used to determine whether the thread is in a new state or in a dead state. If so, it returns false.
When an already running thread does not enter a dead state, do not assign an entity to the thread.
currentThread() returns the thread that is currently using CPU resources
interrupt() is used to "wake up" the thread that calls the sleep() method to sleep

  • Thread class and thread creation

When writing a subclass, you need to override the run() method
. The constructor for creating a thread: Thread(Runnable target), the parameter is an interface of Runnable type, and an instance object needs to be passed to the interface.

  • thread synchronization

Thread synchronization mechanism: When a thread uses the synchronized method, other threads must use the wait() method to wait until the thread finishes using the
method. If other threads do not need to wait when using the synchronized method, the method will be used up. At the same time, execute the notifyAll() method to notify all threads in the waiting state to end waiting.
You cannot use wait(), notify(), notifyAll() methods in non-synchronized methods

  • thread union

Thread B can join thread A through B.join(). Thread A will immediately interrupt execution, and resume execution after waiting for B to finish executing

  • GUI thread

AWT-EventQueue thread is responsible for handling GUI events
AWT-Windows thread is responsible for drawing the form or component to the desktop

  • timer thread

Timer(int a, Object b) create timer
start() start timer
stop() stop timer
restart restart timer

  • Daemon thread

Call the void setDaemon(boolean on) method to set the daemon thread. A thread must set whether it is a daemon thread code hosting
before running. Code screenshot


Guess you like

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