Java Basics-Threading Summary
What is a thread?
Thread: A different running path in a program.
Second, how to create a thread?
There are two ways to create a thread:
First Kind
(1) Define the detailed function class implement Runnable interface, can be called multiple times to achieve data sharing
(2) thread myThread = new Thread (... ) )// number of Runnable interface Types
(3) There is only one method in Runnable
public void Run () {...} Used to define the thread execution body
Another kind
(1) Define a subclass of Thread and override the run () method
Class MyThread extends Thread {public void run () {...} }
(2) Generate objects of this class
MyThread MyThread = new MyThread (...)
What controls can be made on threads?
|
Method |
Function |
|
BOOL IsAlive (MyThread Thread) |
Infer whether the thread is still alive, that is, whether the thread has not yet been terminated.
|
|
int getpririty () |
Get the priority value of a thread |
|
void setpriority (int newpriority) |
Set the priority value of a thread |
|
Thread.Sleep (int sleeptime) |
Specifies the sleep time (in milliseconds) of the current thread |
|
void Join () |
Merges the current thread with the previous primary thread, that is, the A () method of the a thread called the B thread. Let the B thread end and resume the A thread to continue running. |
|
void Yield () |
Yields the CPU, and the current thread enters the ready queue for scheduling. |
|
void Wait () |
The current thread enters the object's wait pool. |
|
void Notify ()/void Notifyall () |
Wakes one / All waiting threads in the wait pool of the object . |
Four, discriminationWait ()with thesleep ()
The reason for these two approaches is that they have one thing in common--pausing a thread's run. But talk about their differences. That's still quite a lot.
Different points:
( 1 ) Wait () is a Object the method of the object; Sleep (int sleeptime) is a Thead () the method of the thread.
( 2 ) Wait () once run, the lock on the current object is freed; Sleep (int) after running, the lock is still in its hands.
( 3 ) Wait () There is no need to specify the length of stay Notify () method or Notifyall () method to wake it up; Sleep (int), among int Specifies the number of milliseconds to sleep, only after this time has elapsed. Wake up, when you get the time slice again, talent continues to run.
Java Basics-Threading Summary