sleep和wait的区别有:
1,来自的类不同,sleep方法来自Thread,wait方法来自Object
2,sleep方法是线程内部方法,没有释放对象的锁,而wait方法释放了对象锁,使得其他线程可以使用同步控制块或者方法。
3,wait,notify和notifyAll是对象操作方法,必须在同步下进行,只有在synchronized里面使用,而sleep可以在任何地方使用。
synchronized(x){
try {
x.wait();或者x.notify()
} catch (InterruptedException e) {
e.printStackTrace();
}
}
4,两者都可以让线程暂停一段时间,但是本质的区别是一个线程的运行状态控制,一个是线程之间的通讯的问题,就需要激活才会进入runing状态。
注意:运行wait和notify的对象不能是基本类型,应该为可引用类型或者javabean
线程启动后是running状态,如过进入等待状态,需要激活才能重新进入running状态
notify():唤醒一个处于等待状态的线程,注意的是在调用此方法的时候,并不能确切的唤醒某一个等待状态的线程,而是由JVM确定唤醒哪个线程,而且不是按优先级。
notifyAll():唤醒所有处入等待状态的线程,并可以理解为把他们排进一个队列,只不过只有头部的线程获得了锁,才能运行,注意!!并不是给所有唤醒线程一个对象的锁,而是让它们竞争,当其中一个线程运行完就开始运行下一个已经被唤醒的线程,因为锁已经转移了。(这个时候是否运行已经不是因为等待状态,而是处于runnning队列中)。
例子:
package com.example.threadnotifydemo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.util.Random;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends android.app.Activity {
private TestClass testClass = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.button);
testClass = new TestClass();
if(testClass.getFlag() ==null)
Log.e("onCreate","the value is null");
else
Log.e("onCreate","the value is"+testClass.getFlag());
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
DemoThread demothread = new DemoThread();
demothread.start();
DemoThread2 demothread2 = new DemoThread2();
demothread2.start();
Random r=new Random();
for (int i = 0;i<10; i++) {
try {
Thread.sleep(1000);//睡眠1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (testClass) {
testClass.setFlag("for:"+Integer.toString(i));
testClass.notifyAll();
//testClass.notify();
Log.e("for:",Integer.toString(i));
}
}
}
});
}
private class TestClass {
private String flag;
public TestClass() {
setFlag(null);
}
public void setFlag(String flag) {
this.flag = flag;
}
public String getFlag() {
return flag;
}
}
private class DemoThread extends Thread {
@Override
public void run() {
Random r=new Random();
while (true) {
synchronized (testClass) {
try {
Log.e("testClass", "111wait");
testClass.wait();
Log.e("DemoThread", "111testClassvalue is " + testClass.getFlag());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.e("DemoThread","111while!!");
}
}
}
private class DemoThread2 extends Thread {
@Override
public void run() {
Random r=new Random();
while (true) {
synchronized (testClass) {
try {
Log.e("testClass", "22wait");
testClass.wait();
Log.e("DemoThread", "22testClassvalue is " + testClass.getFlag());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.e("22DemoThread","111while!!");
}
}
}
}