The difference between the methods of the Thread sleep (), wait (), yield (), join (), and so on

Source: Internet
Author: User
Tags thread class thread stop

The most common methods of manipulating threads are sleep (), join (), yield () (Give way), wait (), notify (), notifyall (), keyword synchronized, and so on.

Since these methods are somewhat similar in function, they are sometimes confusing, and we need to understand their specific principles and reinforce them through specific examples of their own writing, deepening the impression

The difference between the sleep (), yield () method:

Both sleep () and yield () are static methods in the thread class, causing the current running thread to abandon the CPU, but the difference is still larger:
1:sleep causes the current thread (that is, the thread that calls the sleep method to pause for a period of time), gives the other thread the chance to run, and does not take precedence over the other threads, and does not release the resource lock, that is, if there is a synchronized synchronization block
, other threads still cannot access the shared data; Yeild will only give way to the same priority or higher priority threads, and cannot be specified by the user for how long

2: When the thread executes the sleep method, the thread goes to sleep until the time is over and the yield method is executed, directly to the ready state. These will affect the life cycle of the thread (which will be explained in detail later in the blog).

The 3:sleep method needs to throw or catch an exception because the thread may be interrupted during sleep, and the yield method is no exception.

To test a small program:

public class Test7 {
public static void Main (string[] args) {
MyTask4 mt1=new MyTask4 ();
MyTask4 mt2=new MyTask4 ();

Thread t1=new thread (MT1);
T1.setname ("Thread One");

Thread t2=new thread (MT2);
T2.setname ("thread Two");

T1.setpriority (10);
T2.setpriority (1);

T1.start ();
T2.start ();
}
}

Class MyTask4 implements runnable{

@Override
public void Run () {
Remove Current thread
Thread T=thread.currentthread ();
if ("Thread One". Equals (T.getname ())) {
try {
Thread.yield ();
Thread.Sleep (1000);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
for (int i = 0; i < i++) {
System.out.println (T.getname () + ":" +i);
}
}

}

The results of the operation are as follows:


The Join method is used to wait for other threads to end, the currently running thread can invoke the join () method of another thread, and the current process state will be transferred to the suspended state, knowing that another thread runs at the end and that the line friend continues to run.
Note: This method also throws or catches exceptions.

To test a small program:

/* Join method to wait for other threads to end
*/
public class Test8 {
public static void Main (string[] args) throws Interruptedexception {
MyTask5 mt=new MyTask5 ();
Thread T=new thread (MT);
T.setname ("New Thread");
System.out.println (T.isalive ());
T.start ();
System.out.println (T.isalive ());
T.join ();//wait for the T thread to run and then run the main thread
System.out.println ("main thread");
System.out.println (T.isalive ());
}
}
Class MyTask5 implements runnable{

@Override
public void Run () {
int i=0;
while ((i++<10)) {
System.out.println (Thread.CurrentThread (). GetName () + ":" +i);
try {
Thread.Sleep (1000);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}

}

The results of the operation are as follows:



Synchronized keywords:
This keyword is used to protect shared data, although the precondition is to distinguish that data is shared data, each object has a lock flag, when a thread accesses to the object, the data that is synchronized decorated will be "locked" to prevent other threads from accessing it.
When the current thread finishes accessing this piece of data, the lock flag is released and other threads can access it. But if the sync block is too much, it's equivalent to a single thread, so use it flexibly.

Wait (), notify (), Notifyall ()

These 3 methods are all methods under the object class, and are used in conjunction with each other.
These 3 methods are used to coordinate the access of multiple threads to shared data, so they must be used within the synchronized statement block, and if not placed in synchronized, the java.lang.IllegalMonitorStateException exception is reported.
The Synchronized keyword is used to protect shared data from other threads ' access to shared data, but the process of the program is not flexible enough to allow other threads to have a chance when the current thread has not exited the synchronized data block
Access to shared data?
At this point, use these three methods to control flexibly.

The wait () method causes the current thread to pause execution and release the object lock, which is important to release the lock, allowing other threads to enter the synchronized data block and the current thread in the object waiting pool. When the Notify () method is called,
Removes an arbitrary thread from the object's waiting pool and places it in the lock flag waiting pool, noting that
Only the lock flag waits for the thread in the pool to acquire the lock flag, and notify () does not work if there are no threads in the lock flag waiting pool.
Notifyall () removes all the threads waiting for that object from the object waiting pool and puts it in the lock flag waiting pool.

Wait () causes the current thread to wait before other threads call the Notify () method of this object or the Notifyall () method.
Wait (long timeout) causes the current thread to wait before another thread calls this object's notify () method or the Notifyall () method, or exceeds the specified amount of time.
After wait (), the thread releases the "lock flag" that it occupies, so that other shnchronized data in the object where the thread resides can be used by other threads.
Wait () H and notify () because they operate on the object's "lock flags," they must be called in the synchronized function or synchronized block. If the non-synchronized function
or non-synchronized block in the call, although it can be compiled through, but at run time will occur illegalmonitorstateexception exception.

To test a small program:
public class Test6 {
public static void Main (string[] args) {
Fushikang fushikang=new Fushikang ();

Producer p=new Producer (Fushikang);
Producer p2=new Producer (Fushikang);

Sale s=new Sale (Fushikang);
Thread t1=new thread (p);
Thread t2=new thread (p2);
Thread t3=new thread (s);
T1.setname ("Production of One");
T2.setname ("Production of Two");
T3.setname ("sales department");
T1.start ();
T2.start ();
T3.start ();

}
}

Class Producer implements runnable{
Production and consumption are the same resources
Private Fushikang Fushikang;
Public Producer (Fushikang Fushikang) {
This.fushikang=fushikang;
}
@Override
public void Run () {
for (int i=0;i<10;i++) {
iphone iphone=new iphone (i);
Fushikang.product (iphone);
try {
Thread.Sleep (100);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
System.out.println (Thread.CurrentThread (). GetName () + "produced" +iphone.getid () + "phone number");
}
}

}

Class Sale implements runnable{
Private Fushikang Fushikang;

Public Sale (Fushikang Fushikang) {
This.fushikang=fushikang;
}
@Override
public void Run () {
for (int i = 0; i < i++) {
Iphone Iphone=fushikang.sale ();
try {
Thread.Sleep (500);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
System.out.println (Thread.CurrentThread (). GetName () + "SOLD" +iphone.getid () + "phone number");
}
}

}

Class fushikang{
private int index=0;
Private iphone[] Warehouse=new iphone[10];

Public synchronized void Product (iphone iphone) {
Inbound iphone to Warehouse
while (Index==warehouse.length) {
Let the current thread stop until it wakes up by sale
try {
This.wait (); The wait method must be placed in the synchronized block
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
This.notifyall ();
Warehouse[index]=iphone;
index++;

}

Public synchronized Iphone sale () {
while (index==0) {
try {
This.wait ();
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
This.notifyall ();//Wake up multiple
index--;
return Warehouse[index];
}
}

Class iphone{
private int id;

public Iphone (int id) {
This.id=id;
}

public int getId () {
return ID;
}

public void setId (int id) {
This.id=id;
}
}

The difference between the methods of the Thread sleep (), wait (), yield (), join (), and so on

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.