First, the basic concept of the thread
Simply put: the thread is a program in a different execution path, at the same time there is a thread on the cpu only in the implementation, Java in the multi-threading is achieved through the java.lang.Thread class, each threadmethod has its own independent stack space.
Second, java create and start threads
The first
Defined thread class that implements Runnable interface:
Thread myThread = new Thread (target) / / target for the Runnable interface type
Runnable only one method:
public void run (); to define a thread to run the body
The second
Can define a subclass of Thread and override the run method:
clas MyThread extends Thread {
public void run () {}
}
Thread Thread class must be through the implementation of the start () method to start a new thread, if you call run () method calls are methods, not start a new thread, the first approach is recommended to create threads, use the interface more flexible.
Third, the thread state equipment for
Calling thread start () method, the thread into the ready state, Cpu allocated time slice, the thread into the running state, the end of time slice, run () method is not executed, the thread into the blocked state.
Fourth, the basic method of the thread control
isAlive () / / determine whether the thread is still "alive", that is, whether the thread has not terminated
getPriority () / / get value of the priority of the thread
setPriority () / / set the thread priority index
Thread.sleep () / / static method to the current thread to sleep for a few milliseconds
join () / / call the method of a thread, the thread will be merged with the current thread,
/ / Is waiting for the end of the thread, then reply to the current thread running.
yield () / / let the CPU, the current thread into the ready state to wait for scheduling
interrupt () / / Interrupt thread
wait () / / the current thread into the wait pool object
notify () / all / / wake up the object in a wait pool / all waiting threads
Five, sleep method
Static methods Thread
public static void sleep (long millis) throws InterruptedException
Exception must be caught
Thread.currentThread (); / / get the current thread