给了两根线。线程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;
}
}
}当然,无限循环并不是一种很好的做事方式。请帮我找个更好的方法。
发布于 2022-03-22 08:02:17
这是消费者生产者的问题。折叠是一个阻塞队列实现。其他选项: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();
}
}
}
}https://stackoverflow.com/questions/71566545
复制相似问题