java - 在线程间进程中,为什么当子线程首先执行时主线程表现不佳?

标签 java multithreading

我正在学习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()之前执行,那么主线程将永远等待,挂起程序执行。

根据您的代码设计,我猜您想要按照以下特定顺序:

  • 主线程启动T线程和wait()
  • 然后 T 线程运行其代码并调用 notify()
  • 然后主线程打印结果并完成

但是您的代码允许竞争条件,因为第二个项目符号可能会在第一个项目符号结束之前开始和结束,从而导致不良行为。

关于java - 在线程间进程中,为什么当子线程首先执行时主线程表现不佳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42976213/

相关文章:

java - 从字符串中删除项目

java - 为什么这段代码的输出是这样的?

java - 如何过滤包含列表的对象列表?

java - 请解释 Java 内存模型中阐明的初始化安全性

JavaFX-获取网格 Pane 上的点击位置

java - 如何让一段代码先开始-Java小错误/最后一小步

objective-c - 顶点数组对象 (VAO) 能否在 OpenGL ES 中的 EAGLContext 之间共享?

Java是此类线程安全的

c - Visual Studio C 的 _Thrd_create() 和其他线程函数是 Thrd_ C11 函数的实现吗?

multithreading - 使线程使用中央数据库连接的正确方法