20165316 Eighth week study summary

20165316 Eighth week study summary

Textbook learning content summary

Chapter 12

  • A thread's life cycle has four states: new, running, interrupted, and dead
  • create thread
  • Use a subclass of Thread: you must extend Thread and override the run() method.
  • Use the Thread class: Thread(Runnable target) . When creating an object, an instance of a class that implements the Runnable interface must be passed to the constructor, which is called the target object of the created thread (the run() method must be overridden).
  • setPriority(int grade) Adjust thread priority (grade 1~10).
  • Common methods of threading
  • start() can only be called by a thread in a new state
  • run() has no specific content, the user program needs to create a subclass of its own Thread class and rewrite the run() method; after execution, the thread dies
  • The sleep(int millsecond) call puts the high-priority thread to sleep temporarily; must be used in try-catch
  • isAlive() When the thread is in the new and dead state, the method returns false, and when it is in the running state, it returns true
  • currentThread() returns the thread that is using CPU resources
  • interrupt() is used to "wake up" the thread that called the sleep method
  • Thread synchronization: When a thread A uses the synchronized method, other threads must wait until thread A finishes using the method when other threads want to use the synchronized method.
  • Coordinate synchronized threads: The wait() method can interrupt the execution of the thread, make the thread wait, temporarily give up the right to use the CPU, and allow other threads to use this synchronization method. If other threads do not need to wait when using this synchronization method, then when they finish using this synchronization method, they should use the notifyAll() method to notify all waiting threads to end waiting, following the principle of "interrupt before continuing", notify() method Only one of the waiting threads is notified of the end of waiting.
  • Thread union: A thread interrupts its operation and waits until its associated thread B finishes executing, and A thread re-queues to wait for CPU resources in order to resume operation.

Problems encountered and solutions

  • Forgetting to add the Runnable interface causes the Thread method to report an error.

code hosting

Screenshot below

last week's question

no

Guess you like

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