java 执行等待,Java-等待后的执行顺序

all. I have a question for Java wait-notify mechanism. The answer is is there a guaranty that the threads will be executed in this order - from last to the first etc. the result always will be 100, 99, ... , 1 ? This is the snippet of code:

public class Main {

static int counter = 0;

static Object o = new Object();

public static void main(String[] args){

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

new Thread(() -> {

synchronized (o) {

try {

int c = ++counter;

o.wait();

System.out.println("" + c);

Thread.sleep(100);

} catch (Exception e) {

e.printStackTrace();

}

}

}).start();

}

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

synchronized (o) {

new Thread(()-> {

synchronized(o){

System.out.println("LAsttttttttttttttttt");

}

}).start();

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

o.notifyAll();

}

}

}

I run it 10 times and the result is always the same. I coudn't find anything about this in internet. And one more question - when we have 100 threads waiting, when we notifyAll, is there a guaranty that first one of waiting threads will be executed, after then a second one and after all 100 waiting threads are executed, other waiting methods(which were in synchronized block, but don't have wait() in their body), will be executed after that (after all 100 threads that were waiting are executed). Or notifyAll only guaranty that all waiting threads will start fighting with every method which is synchronized by this object? I thing that this is the answer :

"The awakened threads will not be able to proceed until the current

* thread relinquishes the lock on this object. The awakened threads

* will compete in the usual manner with any other threads that might

* be actively competing to synchronize on this object; for example,

* the awakened threads enjoy no reliable privilege or disadvantage in

* being the next thread to lock this object."

But I want to be sure that I understand what's going on when we have wait-notify.

Thanks in advance.

解决方案

No . .there is no guarantee that a set of awoken threads will be executed in any particular order. (This may happen in order because of a particular implementation of JVM or the speed of the computer the program is run on, or many other load based variables. However, there is no language guarantee.)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值