在2个线程之间传递值而不会互相干扰

时间:2014-05-01 17:43:37

标签: java multithreading runnable

我正在使用两个不同的线程创建2个类。并将队列值从线程1传递给线程2,但我没有得到任何东西。

主题1

public class Thread1 implements Runnable {
    BlockingQueue queue = new LinkedBlockingQueue<>();

    public void run() {
        for(int i=0; i<=10; i++) {
            try {
                queue.put(i+2);
                System.out.println("Thread 1");
            } catch (InterruptedException ex) {
                Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

主题2

public class Thred2  implements Runnable {
    Thread1 Thread1 = new Thread1();
    public void run() {
        for(int i=0; i<=10; i++) {
            try {
                System.out.println("Thread 2" + Thread1.queue.take());
            } catch (InterruptedException ex) {
                Logger.getLogger(Thred2.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

主要功能

public class Test {
    public static void main(String[] args) {
        Thread t1 = new Thread(new Thread1());
        Thread t2 = new Thread(new Thred2());
        t1.start();
        t2.start();
    }
}

1 个答案:

答案 0 :(得分:2)

在您的代码中,您将在 main 方法中创建 Thread1 对象,并为的一个实例创建另一个 Thread1 对象> Thred2 。这两个 Thread1 对象是独立的。特别是,两个对象中的每一个都有自己的 LinkedBlockingQueue

您必须以这样的方式更改代码, Thread1 Thred2 使用相同的 LinkedBlockingQueue 。例如,通过以下方式:

我正在使用两个不同的线程创建2个类。并将队列值从线程1传递给线程2,但我没有得到任何东西。

public class Thread1 implements Runnable {
    private final BlockingQueue queue;
    public Thread1(BlockingQueue queue) { this.queue = queue; }
    public void run() {
        for(int i=0; i<=10; i++) {
            try {
                queue.put(i+2);
                System.out.println("Thread 1");
            } catch (InterruptedException ex) {
                Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

public class Thred2  implements Runnable {
    private final BlockingQueue queue;
    public Thred2(BlockingQueue queue) { this.queue = queue; }
    public void run() {
        for(int i=0; i<=10; i++) {
            try {
                System.out.println("Thread 2" + queue.take());
            } catch (InterruptedException ex) {
                Logger.getLogger(Thred2.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

public class Test {
    public static void main(String[] args) {
        BlockingQueue queue = new LinkedBlockingQueue<>();
        Thread t1 = new Thread(new Thread1(queue));
        Thread t2 = new Thread(new Thred2(queue));
        t1.start();
        t2.start();
    }
}