java - 线程的意外行为

标签 java multithreading concurrency parallel-processing synchronization

我正在尝试实现 thread2 应该首先完成,然后是 thread1,为此 O 正在使用 join() 方法。但是,如果我取消注释 thread1 类的 try block 中存在的 System.out.println() 。然后 代码给出空指针异常。为什么在 try block 中我需要添加行,添加行代码开始工作没有任何意义。

演示课

public class Demo {

    public static void main(String[] args) throws InterruptedException {

        Thread1 t1 = new Thread1();
        Thread2 t2 = new Thread2();
        t1.start();
        t2.start();

        System.out.println("main Thread");
        Thread.sleep(10);
    }
}

线程1类

public class Thread1 extends Thread {
    @Override
    public void run() {
        try {
//            System.out.println(); // on adding anyline, this whole code works!!, uncommenting this line of code give NPE
            Thread2.fetcher.join();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 5; i++) {

            System.out.println("in thread1 class, Thread-1 ");
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

线程2类

public class Thread2 extends Thread {

    static Thread fetcher;

    @Override
    public void run() {

        fetcher= Thread.currentThread(); // got the thread2
        for (int i = 0; i < 5; i++) {
            System.out.println("in thread2 class, Thread-2");
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

程序的输出

in thread2 class Thread-2
Exception in thread "Thread-0" java.lang.NullPointerException
    at org.tryout.Thread1.run(Thread1.java:22)
in thread2 class Thread-2
in thread2 class Thread-2
in thread2 class Thread-2
in thread2 class Thread-2

最佳答案

它纯粹是靠“纯粹的运气”

System.out.println();

内部调用 synchronized,它作为延迟工作,为 Thread 2 其字段 fetcher 提供 足够 时间> 在:

fetcher= Thread.currentThread(); // got the thread2

为了避免这种race-condition,您需要确保 Thread 2Thread 1 之前设置字段 fetcher 访问它。为此,您可以使用 CyclicBarrier .

??A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.** CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.

首先,为将要调用它的线程数创建一个屏障,即 2 个线程:

CyclicBarrier barrier = new CyclicBarrier(2);

使用 CyclicBarrier,您可以强制 Thread 1 在访问其字段 fetcher 之前等待 Thread 2 :

    try {
        barrier.await(); // Let us wait for Thread 2.
        Thread2.fetcher.join();
    } catch (InterruptedException | BrokenBarrierException e) {
        // Do something 
    }

Thread 2 在设置 fetcher 字段后也会调用屏障,相应地:

    fetcher = Thread.currentThread(); // got the thread2
    try {
        barrier.await();
    } catch (InterruptedException | BrokenBarrierException e) {
        e.printStackTrace();
    }

一旦调用了屏障,两个线程就会继续工作。

一个例子:

public class Demo {

    public static void main(String[] args) throws InterruptedException             { 
        CyclicBarrier barrier = new CyclicBarrier(2);
        Thread1 t1 = new Thread1(barrier);
        Thread2 t2 = new Thread2(barrier);
        t1.start();
        t2.start();
        System.out.println("main Thread");
        Thread.sleep(10);
    }
}

public class Thread1 extends Thread {
    final CyclicBarrier barrier;

    public Thread1(CyclicBarrier barrier){
        this.barrier = barrier;
    }

    @Override
    public void run() {
        try {
            barrier.await();
            Thread2.fetcher.join();
        } catch (InterruptedException | BrokenBarrierException e) {
            // Do something 
        }
        for (int i = 0; i < 5; i++) {
            System.out.println("in thread1 class, Thread-1 ");
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class Thread2 extends Thread {
    static Thread fetcher;
    final CyclicBarrier barrier;

    public Thread2(CyclicBarrier barrier){
        this.barrier = barrier;
    }

    @Override
    public void run() {

        fetcher = Thread.currentThread(); // got the thread2
        try {
            barrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 5; i++) {
            System.out.println("in thread2 class, Thread-2");
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

如果您的代码不是用于教育目的,并且您不会被迫使用任何特定的同步机制来进行学习。在当前上下文中,您可以简单地将 thread 2 作为 thread 1 的参数传递,然后直接在其上调用 join,如下所示:

public class Demo {
    public static void main(String[] args) throws InterruptedException {
        Thread2 t2 = new Thread2();
        Thread1 t1 = new Thread1(t2);
        t1.start();
        t2.start();
        System.out.println("main Thread");
        Thread.sleep(10);
    }
}

public class Thread1 extends Thread {
    final Thread thread2;

    public Thread1(Thread thread2){
        this.thread2 = thread2;
    }

    @Override
    public void run() {
        try {
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 5; i++) {
            System.out.println("in thread1 class, Thread-1 ");
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class Thread2 extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("in thread2 class, Thread-2");
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
} 

关于java - 线程的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66589095/

相关文章:

java - 在另一个ArrayList中查找JButton源

java.util.ConcurrentLinkedQueue

c - 如何在循环时扫描输入(C 程序)

java - Java 中的信号量。为什么第二个线程不等待?

无法使用在 c 中处理多个客户端的服务器在客户端之间平均分配工作

阐明 GNU C 库如何定义不可重入函数

java - Spring Webflux如何验证所有步骤是否执行成功

java - 监控 Tomcat StandardThreadExecutor 的队列大小 (MBean)

Java 序列化 1.4 与 1.6

ios - IOS重启主线程