您的位置:首页 > 编程语言 > Java开发

JAVA 线程等待唤醒,wait and notify

2013-09-13 09:02 651 查看
wait,notify操作是同一个对象锁,简单例子如下

package com.cienet.wangbin.test;

public class Test7 {

/**

* @param args

*/

public static void main(String[] args) {

new Thread1().start();

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

}

new Thread2().start();

}

static class Thread1 extends Thread {

@Override

public void run() {

super.run();

int count = 10;

synchronized (Test7.class) {

for (int i = 0; i < count; i++) {

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

}

if (i == 2) {

try {

Test7.class.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println(i);

}

}

}

}

static class Thread2 extends Thread {

@Override

public void run() {

super.run();

int count = 10;

synchronized (Test7.class) {

for (int i = 0; i < count; i++) {

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

}

if (i == 5) {

Test7.class.notify();

}

System.out.println("b" + i);

}

}

}

}

}

如上结果可知,wait是会释放锁的,而notify不会释放锁,当调用它的时候,不能够直接唤醒wait住的线程,而是先等其本身执行完毕后才释放锁。wait住的资源才能获取锁,继续执行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐