When a thread plays a major role: when the I/O that a thread executes is blocked, other threads in the same process can use the CPU to compute. In this way, the execution efficiency of the program is improved.
status : Running, Ready (waiting to be called), blocking (Waiting for I/O resources)
two ways to create :
- inherit the thread class and override the Run () method in it (this method is appropriate when a class does not inherit other classes)
- Implement the Runnable interface and implement the Run () method (which is appropriate when a class has inherited another Class)
Pass various parameters by using a custom construction method. Start: Call the Start () method after getting the thread object.
public class MyThread1 extends Thread {public MyThread1 (String name) { super (name); } public void Run () { System.out.println (This.getname ()); } public static void Main (string[] args) { Thread t1 = new MyThread1 ("a three"); T1.start (); } } public class MyThread implements Runnable {private String name; Public MyThread (String name) { this.name = name;} @Override public void Run () { System.out.println (name); } public static void Main (string[] args) { thread tt1 = new Thread (New MyThread ("Zhang San")); Tt1.start (); } }
wait and wake mechanism: Using Object.wait () and Object.notify (), the join () method must be called in a synchronous method or synchronous block to wait for the termination of another thread, such as:
A.join (); System.out.print ("End"); Wait for thread A to finish before printing "End"
the difference between sleep () and wait ():
- Sleep (): Consumes CPU resources or is scheduled to go into ready state
- Wait (): does not consume CPU resources and waits for notify () to wake up
(original article, reprint please specify the CSDN blog from Clement-xu)
Copyright NOTICE: This article is the original article, reprint please indicate the CSDN blog which is transferred from Clement-xu.
Threads and how they are created