我正在尝试使用多个线程将多个程序包发送到服务器。我的目标是一次发送包裹。我在函数启动之前创建了一个线程池。
有一个生产者线程将新程序包插入队列和使用者线程(其中有10个),使用者线程创建连接并在最佳情况下发送程序包。
但是在我的情况下,它是一个接一个地发生的。
private static BlockingQueue jobQueue = new LinkedBlockingQueue(10);
private static Object lock = new Object();
ExecutorService producers = Executors.newFixedThreadPool(1);
ExecutorService consumers = Executors.newFixedThreadPool(10);
producers.submit(() -> {
while (true) {
Thread.sleep(2000);
int value = new Random().nextInt(20);
System.out.println("Added to list: " + value);
jobQueue.put(value);
}
});
consumers.submit(() -> {
while (true) {
if (!LB.getUpHostList().isEmpty()) {
Host host = LB.getUpHostList().get(0);
if (host.isActive()) {
String message;
message = jobQueue.take().toString();
System.out.println("Removed from list: " + message);
boolean isConnected = connect(host, message, 1);
if (!isConnected) {
System.out.println("SAVED");
jobQueue.put(Integer.parseInt(message));
lock.notifyAll();
}
}
}
}
});
消费线程必须以并行方式工作。我想消费者线程中应该有一个可调用的列表,但我没有明白这一点
public static boolean connect(Host host, String message, int mode) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap clientBootstrap = new Bootstrap();
clientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 100);
clientBootstrap.group(group);
clientBootstrap.channel(NioSocketChannel.class);
clientBootstrap.remoteAddress(new InetSocketAddress(host.getIp(), host.getPort()));
clientBootstrap.handler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel socketChannel) {
//TODO, TIMEOUT BILGISI ILE DOLDUR BURAYI
//socketChannel.pipeline().addLast(new ReadTimeoutHandler(1));
//socketChannel.pipeline().addLast("idleStateHandler", new IdleStateHandler(2, 2, 4));
socketChannel.pipeline().addLast(new FalconClientHandler(host, message, mode));
}
});
ChannelFuture channelFuture = clientBootstrap.connect().sync();
channelFuture.channel().closeFuture().sync();
return true;
} catch (Exception e) {
System.err.println("Connection timed out --> " + e);
host.setActive(false); //connection kurulamadı demektir. Bir sonraki mesaj geldiğinde bu hostun açılıp açılmadığı denenecek.
return false;
} finally {
group.shutdownGracefully().sync();
if (mode == 0) { //arka planda sunucu hep ayakta olmalı. Mode 0 da asla bağlantı kesilmemeli. Kesiliyorsa host kapanmıştır.
host.setActive(false);
return false;
}
}
}
谢谢