- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在学习java中的线程并编写了以下代码。这里:我正在创建两个线程(main 和 t),并且我想实现线程间通信。这是两种情况:
1)如果主线程首先执行/继续,则主线程获取对象“t”上的锁,释放锁并进入等待状态(
synchronized (t) {
System.out.println("waiting " + Thread.currentThread().getName() + " " + System.currentTimeMillis());
t.wait();
}
)。子线程发生并完成其工作并通知主线程。主线程启动并打印最终输出System.out.println(t.total)
。对我来说没问题。
2)如果子线程先执行,则子线程完成其工作(
synchronized (this) {
for (int i = 0; i < 100 ; i++) {
total = total + i;
}
System.out.println("------------" + Thread.currentThread().getName() + "calling notify" + System.currentTimeMillis());
this.notify();
}
) 并最后调用通知。当它的调用通知时会发生什么,因为没有人在等待?下一个问题是主线程是否正在等待生命周期?如果不是那么为什么不等待。
下面是代码。
public class Test {
public static void main(String[] args) throws InterruptedException {
T t = new T();
t.setPriority(10);
t.start();
System.out.println();
System.out.println();
synchronized (t) {
System.out.println("waiting " + Thread.currentThread().getName() + " " + System.currentTimeMillis());
t.wait();
}
System.out.println(t.total);
}
}
class T extends Thread {
public int total = 0;
public void run() {
synchronized (this) {
for (int i = 0; i < 100 ; i++) {
total = total + i;
}
System.out.println("------------" + Thread.currentThread().getName() + "calling notify" + System.currentTimeMillis());
this.notify();
}
}
}
问题:当子线程首先运行时,程序(主线程)成功结束/完成,或者主线程等待,为什么???
以下是输出:
------------Thread-0calling notify1490271423920
waiting main 1490271423921
在这种情况下,主线程处于 Activity 状态。
------------Thread-0calling notify1490272176789
waiting main 1490272176789
4950
在这种情况下,主线程成功结束。为什么会这样?
谢谢。
最佳答案
What happen when its call notify, because no one is waiting??
什么也没发生。
next question is Main thread is waiting life time or not?? If not then why not waiting.
抱歉,我没听懂你的问题。
Questions: When child thread run first some times program(Main thread) ended/complete successfully or some time Main thread goes for waiting, Why???
如果this.notify()
在t.wait()
之前执行,那么主线程将永远等待,挂起程序执行。
根据您的代码设计,我猜您想要按照以下特定顺序:
wait()
notify()
但是您的代码允许竞争条件,因为第二个项目符号可能会在第一个项目符号结束之前开始和结束,从而导致不良行为。
关于java - 在线程间进程中,为什么当子线程首先执行时主线程表现不佳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42976213/
有人可以向我澄清主线 DHT 规范中的声明吗? Upon inserting the first node into its routing table and when starting up th
我正在尝试使用 USB 小工具驱动程序使嵌入式设备作为 MTP 设备工作。 我知道 Android 从大容量存储设备切换到 MTP 设备已经有一段时间了,并且找到了 source code for M
我是一名优秀的程序员,十分优秀!