本文目录一览:
java线程wait方法
wait和notify是用在多线程竞争同一锁资源的情况下使用的。
你这段代码实际是个单线程,这个线程自己把自己阻塞了,自然不可能自己把自己唤醒。
你的意图怎么实现呢?需要加入另外一个线程,下面是我仿照你的意图写的一段代码,供参考下
public class A
{
public A(){
final A a = this;
Thread th1 = new Thread(){
@Override
public void run(){
//一直循环,去尝试着唤醒a
try
{
this.sleep(10000);
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}//为检查是不是能真正实现唤醒a,等待10000毫秒,此时保证a已经处于等待状态中。
while(true){
/**
* 用notify唤醒的线程必须是持有当前锁对象的线程
*/
synchronized (a){
a.notify();
}
}
}
};
th1.setDaemon(true);//这句也是必须的,将th1设为守护线程,保证在唤醒a以后,所有活动的线程都为守护线程,jvm能及时推出
th1.start();//和a.run的顺序不可以换
this.run();
}
public static void main(String[] args)
{
new A();
}
public void run()
{
/**
* 这里可以换成这样,直接锁住this就行了
*/
synchronized (this)
{
try
{
this.wait();//阻塞当前的线程
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
System.out.println(“1”);//执行finally
}
}
}
}
java中wait方法怎么条用
wait方法用在 synchronized 方法或者 synchronized块中。一般在判断语句中,如果某条件被触发,让当前线程wait并释放对象的锁。此时可以让其他线程可以对用以对象调用synchronized方法。直到调用 notify或者notifyAll后 wait的线程才有可能执行。所以一般wait 和 notify是成对出现的。
java wait的用法
wait是Object的方法,也就是说可以对任意一个对象调用wait方法,调用wait方法将会将调用者的线程挂起,直到其他线程调用同一个对象的notify方法才会重新激活调用者,例如:
//Thread 1
try{
obj.wait();//suspend thread until obj.notify() is called
}
catch(InterrputedException e) {
}
java中的sleep和wait的区别
sleep和wait的区别:
1、sleep的意思是:睡,睡觉,睡眠。
2、wait的意思是:等候,推迟,延缓等待,耽搁,伺候用餐。
拓展资料
sleep的用法
1、They were exhausted from lack of sleep
由于缺乏睡眠,他们非常疲惫。
2、During the car journey, the baby slept
坐车来的路上,宝宝睡着了。
3、I think he may be ready for a sleep soon.
我想他也许很快就要睡一觉了。
4、I can’t get to sleep with all that singing.
那些歌声搅得我无法入睡。
5、I didn’t lose too much sleep over that investigation.
我并不太担心那个调查。
wait
1、I walk to a street corner and wait for the school bus
我走到街角等校车。
2、There’ll be a car waiting for you
会有辆汽车等你。
3、I want to talk to you, but it can wait
我想和你谈谈,但可以晚点再说。
4、If you think this all sounds very exciting, just wait until you read the book
如果你觉得所有这些听起来令人兴奋,那就等着去读这本书吧。
5、’Wait a minute!’ he broke in. ‘This is not giving her a fair hearing!’
“等一下,”他插嘴说,“这没有给她一个公平的解释机会!”
原创文章,作者:KCDIS,如若转载,请注明出处:https://www.506064.com/n/325407.html