繁体   English   中英

如何确保在 java 中一个线程始终先于其他线程运行? 给定两个线程。 我需要确保线程 1 始终领先于线程 2

[英]How do I ensure that one thread always run ahead of other in java? Given two threads. I need to make sure that Thread 1 always leads Thread 2

给定两个线程。 线程 1:从 1 打印到 100 线程 2:从 1 打印到 100 我需要确保线程 1 从不打印线程 2 尚未打印的任何数字。

请帮我解决一下这个。 提前致谢。 (——在我对维森科技的采访中被问到)

我尝试了以下方法。

package threadTutor;

public class ThreadLeader {

    public static void main(String[] args) throws InterruptedException {
        Leader lead = new Leader(100);
        Follower foll = new Follower(100);
        foll.start();
        lead.start();
        foll.join();
        lead.join();        
    }

}

class Leader extends Thread{
    static int start;
    static int end;
    static int pos;
    Leader(int end){
        Leader.end = end;
    }
    public void run() {
        for(int i=start;i<end;i++) {
            System.out.println("Leader is printing "+i);
            Leader.pos=i;
        }
    }
}
class Follower extends Thread{
    static int start;
    static int end;
    static int pos;
    Follower(int end){
        Follower.end = end;
    }
    public void run() {
        while(true) {
            if(Follower.pos<=Leader.pos) {
                System.out.println("Follower is printing "+pos);
                pos++;
            }
            if(Follower.pos==Follower.end) break;
        }       
    }
}

但是当然,无限的 while 循环不是做事的好方法。 请提供更好的方法。

这是一个消费者-生产者问题。 以下是阻塞队列的实现。 其他选项: https://www.geeksforgeeks.org/producer-consumer-solution-using-threads-java/

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ThreadLeader {

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
        Leader lead = new Leader(queue, 100);
        Follower foll = new Follower(queue, 100);
        foll.start();
        lead.start();
        foll.join();
        lead.join();
    }

}

class Leader extends Thread {
    private BlockingQueue<Integer> queue;
    private int num;

    Leader(BlockingQueue<Integer> queue, int num) {
        this.queue = queue;
        this.num = num;
    }

    public void run() {
        for (int i = 1; i <= num; i++) {
            System.out.println("Leader is printing " + i);
            queue.offer(i);
        }
    }
}

class Follower extends Thread {
    private BlockingQueue<Integer> queue;
    private int num;

    Follower(BlockingQueue<Integer> queue, int num) {
        this.queue = queue;
        this.num = num;
    }

    public void run() {
        for (int i = 0; i < num; i++){
            try {
                System.out.println("Follower is printing " + queue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM