线程的意外行为

Man*_*rma 3 java parallel-processing concurrency multithreading synchronization

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

演示课

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

线程 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();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

}
Run Code Online (Sandbox Code Playgroud)

程序的输出

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
Run Code Online (Sandbox Code Playgroud)

dre*_*ash 6

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

System.out.println();
Run Code Online (Sandbox Code Playgroud)

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

fetcher= Thread.currentThread(); // got the thread2
Run Code Online (Sandbox Code Playgroud)

为了避免这种竞争条件,您需要确保在访问Thread 2该字段fetcher之前设置该字段Thread 1。为此,您可以使用CyclicBarrier 等

??一种同步辅助工具,它允许一组线程相互等待以到达公共屏障点。** CyclicBarriers 在涉及固定大小的线程组的程序中很有用,这些线程偶尔必须相互等待。屏障被称为循环的,因为它可以在等待线程被释放后重新使用。

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

CyclicBarrier barrier = new CyclicBarrier(2);
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

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

一个例子:

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();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您的代码不是用于教育目的,并且您没有强制使用任何特定的同步机制来进行学习。在当前上下文中,您可以简单地传递 的thread 2as 参数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();
            }
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)