我有一个线程可以将连接添加到列表中。当列表变大时,我的应用程序需要选择2个随机元素。
此后,程序会对连接进行一些操作,然后将两个连接从列表中删除。
我已经尝试过运行一个单独的线程,并检查列表是否大于2个元素。
当其较大时,它将从列表中选择2个随机元素并对其执行操作,然后将其从列表中删除。
是否有更好的方法可以以设计模式进行此操作?我认为运行另一个线程继续检查list是否大于2并不是一个好的解决方案。
答案 0 :(得分:1)
您可以解决生产者消费者问题,其中一个线程正在检查List的大小,而当大小达到2时,其他线程将开始从列表中消耗(删除)您的解决方案。对线程的添加和删除都应通过同步块执行,以免出现差异。
您可以尝试以下方法解决您的问题。
`
import java.util.LinkedList;
public class Threadexample
{
public static void main(String[] args) throws InterruptedException {
// Object of a class that has both produce()
// and consume() methods
final PC pc = new PC();
// Create producer thread
Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
pc.produce();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});
// Create consumer thread
Thread t2 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
pc.consume();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});
// Start both threads
t1.start();
t2.start();
// t1 finishes before t2
t1.join();
t2.join();
}
// This class has a list, producer (adds items to list
// and consumer (removes items).
public static class PC
{
// Create a list shared by producer and consumer
// Size of list is 2.
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;
// Function called by producer thread
public void produce() throws InterruptedException
{
int value = 0;
while (true)
{
synchronized (this)
{
// producer thread waits while list
// is full
while (list.size()==capacity)
wait();
System.out.println("Producer produced-"
+ value);
// to insert the jobs in the list
list.add(value++);
// notifies the consumer thread that
// now it can start consuming
notify();
// makes the working of program easier
// to understand
Thread.sleep(1000);
}
}
}
// Function called by consumer thread
public void consume() throws InterruptedException
{
while (true)
{
synchronized (this)
{
// consumer thread waits while list
// is empty
while (list.size()==0)
wait();
//to retrive the ifrst job in the list
int val = list.removeFirst();
System.out.println("Consumer consumed-"
+ val);
// Wake up producer thread
notify();
// and sleep
Thread.sleep(1000);
}
}
}
}
} `
在这里看看 https://www.geeksforgeeks.org/producer-consumer-solution-using-threads-java/