Java 线程的意外行为

Java 线程的意外行为,java,multithreading,concurrency,parallel-processing,synchronization,Java,Multithreading,Concurrency,Parallel Processing,Synchronization,我试图实现thread2应该首先完成,然后是thread1,为此我使用了join()方法。但是如果我取消注释thread1类的try块中存在的System.out.println()。然后 代码给出空指针异常。为什么在try块中我需要添加行,添加行代码开始工作毫无意义 演示课 public class Demo { public static void main(String[] args) throws InterruptedException { Thread1

我试图实现thread2应该首先完成,然后是thread1,为此我使用了
join()
方法。但是如果我取消注释thread1类的try块中存在的
System.out.println()
。然后 代码给出空指针异常。为什么在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);
    }
}
线程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
的字段
取数器提供足够的时间:

fetcher= Thread.currentThread(); // got the thread2
为了避免这种竞争情况,您需要确保
线程2
线程1
访问字段之前设置字段
获取程序。对于这种情况,除其他外,请使用

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

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

CyclicBarrier barrier = new CyclicBarrier(2);
然后,使用CyclicBarrier,您可以强制
线程1
等待
线程2
,然后再访问其字段
取数器

    try {
        barrier.await(); // Let us wait for Thread 2.
        Thread2.fetcher.join();
    } catch (InterruptedException | BrokenBarrierException e) {
        // Do something 
    }
线程2
在设置字段
获取程序后也会调用屏障,因此:

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

这将允许您的代码正常工作。线程启动之间没有足够的时间来允许
fletcher
初始化

        try {
        
            Thread.sleep(500);
             
            Thread2.fetcher.join();
         }  catch (InterruptedException ie) {
         } 
对于这样简单的事情,睡眠应该起作用。但对于更复杂的线程,适当的同步是关键。您应该知道,线程编程可能是编程中最难调试的方面之一

    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();
            }
        }
    }
}
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();
            }
        }
    }
} 
        try {
        
            Thread.sleep(500);
             
            Thread2.fetcher.join();
         }  catch (InterruptedException ie) {
         }