java 连接两个arraylist,java – 在两个线程之间共享一个ArrayList?

既然你已经使用了动词’push’和’poll’,那么你似乎在寻找一个不是列表的队列.

因此,我认为您正在寻找记录为here的ConcurrentLinkedQueue.

它允许您让UserRequest对象提供它并使用Poller对象来使用它.

虽然看起来你的Poller对象会有很高的CPU占用率,因为没有任何等待是开放的:

public class Poller implements Runnable {

Queue colors = new ConcurrentLinkedQueue();

public void poll() {

while(this.colors.isEmpty()){

Thread.currentThread().wait();

}

String color = this.colors.poll();

while(color != null) {

if(color == "") {

//do work

} else {

//do work

}

color = this.colors.poll();

}

}

@Override

public void run() {

colors.offer("Violet");

colors.offer("Green");

colors.offer("Yellow");

colors.offer("Orange");

while(true) {

this.poll();

}

}

}

此代码需要进行一些更改才能运行,但它包含您需要的所有内容.

它的作用非常简单:它一直保持轮询,直到没有剩余元素为止.

一旦发生这种情况,Poller对象会询问它当前的Thread是否处于休眠状态,因为没有任何点可以在没有Queue中的元素的情况下运行.

public class UserRequest implements Runnable {

@Override

public void run() {

String request;

Scanner input = new Scanner(System.in);

while(true) {

System.out.println("Please enter request:");

request = input.nextLine();

try {

//do something

} catch(IOException e) {

e.printStackTrace();

} finally {

this.notifyAll(); // Notifies all sleeping threads to wake up

}

}

}

如果您注意到,我只向您的UserRequest类添加了notifyAll调用.为什么?非常简单:notifyAll唤醒所有等待的线程,这正是所有没有元素的Poller正在做的事情.

一旦被调用,Pollers将唤醒,检查他们的颜色队列是否有元素并使用它们.如果Queue没有元素,它们将再次休眠,直到UserRequest再次唤醒它们,依此类推.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值