线程的意外行为

Unexpected behaviour of Threads

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

演示 class

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 class

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 class

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 在访问其字段之前等待 Thread 2 fetcher:

    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();
            }
        }
    }
} 

这应该能让您的代码正常工作。线程启动之间的时间不足,无法 fletcher 进行初始化。

        try {
        
            Thread.sleep(500);
             
            Thread2.fetcher.join();
         }  catch (InterruptedException ie) {
         } 

对于这么简单的事情,睡眠应该有效。但对于更复杂的线程,合适的同步才是关键。而且您应该知道,线程编程可能是编程中最难调试的方面之一。