线程等待
public class Hello {
public static void main(String[] args) {
A a = new A();
new Thread(new MyRun(a)).start();
new Thread(new MyRun1(a)).start();
}
}
class MyRun implements Runnable {
private A a;
public MyRun(A a) {
this.a = a;
}
@Override
public void run() {
synchronized (a) {
a.setTitle("hello");
try {
a.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
a.setNumber(12);
System.out.println(a);
}
}
}
class MyRun1 implements Runnable {
private A a;
public MyRun1(A a) {
this.a = a;
}
@Override
public void run() {
synchronized (a) {
a.setTitle("world");
a.setNumber(24);
a.notifyAll();
System.out.println(a);
}
}
}
class A {
private String title;
private Integer number;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
@Override
public String toString() {
return "A{" +
"title='" + title + '\'' +
", number=" + number +
'}';
}
}
线程等待,obj.wait(),会释放当前的锁,对象的普通方法,obj.wait(超时时间),表示指定时间后可以自动唤醒
线程唤醒,obj.notify(),唤醒一个线程,obj.notifyAll(),唤醒所以线程,obj需要和线程等待的对象一致。
wait和sleep的区别
个人认为:sleep就是一种延缓代码执行的方法,wait是有关多线程的一些高级操作。