gpt4 book ai didi

java thread.sleep() 在我测试时不让处理器时间可供其他线程使用

转载 作者:行者123 更新时间:2023-11-29 06:26:59 24 4
gpt4 key购买 nike

<分区>

当我使用Thread.sleep()时,我发现当当前线程调用sleep()方法时,其他线程无法获得处理器时间来调用它们自己的。但是我从 Oracle's doc 得到了 sleep() 方法的信息。相反,所以我很困惑。

这是我的代码:

class ThreadTest {

private Runnable mRunnable = () -> {
println("from runnable start run");
println("from runnable start end");
};

private class TestThread extends Thread {
@Override
public void run() {
super.run();
println("from Thread start run");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
println("from Thread end");
}
}


private void println(String info) {
System.out.println(getDate() + " : "+info);
}

private String getDate() {
SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
sdf.applyPattern("yyyy-MM-dd HH:mm:ss a");// a为am/pm的标记
Date date = new Date();// 获取当前时间
return sdf.format(date);
}

void testThread() {
TestThread thread= new TestThread();
thread.run();
for (int i = 0; i < 10; i++) {
new Thread(mRunnable).run();
}
}
}

结果是

2018-11-09 18:15:20 PM : from Thread start run

2018-11-09 18:15:23 PM : from Thread end

2018-11-09 18:15:23 PM : from runnable start run

2018-11-09 18:15:23 PM : from runnable start end

2018-11-09 18:15:23 PM : from runnable start run

2018-11-09 18:15:23 PM : from runnable start end

2018-11-09 18:15:23 PM : from runnable start run

2018-11-09 18:15:23 PM : from runnable start end

2018-11-09 18:15:23 PM : from runnable start run

2018-11-09 18:15:23 PM : from runnable start end

2018-11-09 18:15:23 PM : from runnable start run

2018-11-09 18:15:23 PM : from runnable start end

2018-11-09 18:15:23 PM : from runnable start run

2018-11-09 18:15:23 PM : from runnable start end

2018-11-09 18:15:23 PM : from runnable start run

2018-11-09 18:15:23 PM : from runnable start end

2018-11-09 18:15:23 PM : from runnable start run

2018-11-09 18:15:23 PM : from runnable start end

2018-11-09 18:15:23 PM : from runnable start run

2018-11-09 18:15:23 PM : from runnable start end

2018-11-09 18:15:23 PM : from runnable start run

2018-11-09 18:15:23 PM : from runnable start end

希望有人能帮忙

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com