从我的主要我开始两个线程称为生产者和消费者。两者都包含while(true)循环。生产者循环是UDP服务器,因此它不需要睡眠。我的问题出现在Consumer循环中。使用者循环从链接队​​列中删除对象并将其传递给函数以进行进一步处理。从研究结果来看,在循环中使用线程休眠不是一个好习惯,因为有时O / S不会在设置时间结束时释放。如果我在应用程序理想的情况下删除线程休眠,则将CPU拖动到20%到30%。

class Producer implements Runnable {

private DatagramSocket dsocket;

FError fer = new FError();

int port =1548;

ConcurrentLinkedQueue queue;

Producer(ConcurrentLinkedQueue queue){

this.queue = queue;

}

@Override

public void run() {

try {

// Create a socket to listen on the port.

dsocket = new DatagramSocket(port);

// Create a buffer to read datagrams into.

byte[] buffer = new byte[30000];

// Create a packet to receive data into the buffer

DatagramPacket packet = new DatagramPacket(buffer,

buffer.length);

while (true) {

try {

// Wait to receive a datagram

dsocket.receive(packet);

//Convert the contents to a string,

String msg = new String(buffer, 0, packet.getLength());

int ltr = msg.length();

// System.out.println("MSG =" + msg);

if(ltr>4)

{

SimpleDateFormat sdfDate = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy

Date now = new Date();

String strDate = sdfDate.format(now);

//System.out.println(strDate);

queue.add(msg + "&" + strDate);

// System.out.println("MSG =" + msg);

}

// Reset the length of the packet before reusing it.

packet.setLength(buffer.length);

} catch (IOException e) {

fer.felog("svr class", "producer", "producer thread",e.getClass().getName() + ": " + e.getMessage());

dsocket.close();

break;

}

}

} catch (SocketException e) {

fer.felog("svr class", "producer","Another App using the udp port " + port, e.getClass().getName() + ": " + e.getMessage());

}

}

}

class Consumer implements Runnable {

String str;

ConcurrentLinkedQueue queue;

Consumer(ConcurrentLinkedQueue queue) {

this.queue = queue;

}

@Override

public void run() {

while (true) {

try {

while ((str = queue.poll()) != null) {

call(str); // do further processing

}

} catch (IOException e) {

ferpt.felog("svr class", "consumer", "consumer thread", e.getClass().getName() + ": " + e.getMessage());

break;

}

try {

Thread.sleep(500);

} catch (InterruptedException ex) {

ferpt.felog("svr class", "consumer","sleep", ex.getClass().getName() + ": " + ex.getMessage());

}

}

}

}

Logo

一站式 AI 云服务平台

更多推荐