Cpu使用率过高,高达95%
我的项目有需求,需要不断阅读条码数据,就像商品超市扫描仪一样用条形码扫描枪,然后将数据输入到键盘,但遇到了问题,长时间连续扫描,CPU使用率会非常高,甚至达到了95%,我已经将线程设置为一个循环睡眠,但未能解决这个问题。Cpu使用率过高,高达95%
我一直在问这个问题,但是可能代码太乱了,影响大家阅读,现在简化代码,希望你能帮助我,非常感谢你;
有时CPU扫描的几个小时会占用太高的时间,但有时在那里有几天。抓住logcat日志发现sleep方法有时不会被执行,如果不是连续执行会导致CPU使用率过高,但不知为什么睡眠方法不会执行。
private void startReceive() {
stopReceive = false;
new Thread(new Runnable() {
@Override
public void run() {
int timeout = 1000;
while (!stopReceive) {
if (mUsbDeviceConnection != null) {
try {
byte[] receiveBytes = new byte[64];
int value = mUsbDeviceConnection.bulkTransfer(mUsbEndpoint, receiveBytes,
receiveBytes.length, timeout);
if (value > 0) {
for (int i = 2; !stopReceive && i < receiveBytes.length; i++) {
byte b = receiveBytes[i];
if (b != 0) {
result += new String(new byte[]{b});
}
if (!stopReceive && !result.equals("") && result != null) {
Runtime.getRuntime().exec("input text " + result);
}
}
}
Thread.sleep(100);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}).start();
}
这seemd是主要的线程上运行一个庞大的线程将性能大幅放缓装置。
大作战,你应该不是异步运行,这意味着它会在后台线程运行,并不会影响到UI线程这是问题的现在:
这里的实施将如何看一个例子像:
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// StartReceive code..
stopReceive = false;
new Thread(new Runnable() {
@Override
public void run() {
int timeout = 1000;
while (!stopReceive) {
if (mUsbDeviceConnection != null) {
try {
byte[] receiveBytes = new byte[64];
int value = mUsbDeviceConnection.bulkTransfer(mUsbEndpoint, receiveBytes,
receiveBytes.length, timeout);
if (value > 0) {
for (int i = 2; !stopReceive && i < receiveBytes.length; i++) {
byte b = receiveBytes[i];
if (b != 0) {
result += new String(new byte[]{b});
}
if (!stopReceive && !result.equals("") && result != null) {
Runtime.getRuntime().exec("input text " + result);
}
}
}
Thread.sleep(100);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}).start();
return "Done";
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// We're done
}
@Override
protected void onPreExecute() {
// Before starting operation
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
如何启动线程:
LongOperation longOp = new LongOperation();
longOp.execute();
我试图使用AsyncTask,它不起作用; – Victor
@Victor你的意思是'它不起作用'? CPU使用率是否仍然过高或者代码本身有问题? – timbillstrom
CPU使用率仍然过高,CPU占用率仍然很高,我来看看AsyncTask的来源,内部维护一个BlockingQueue,所以对线程管理确实有所帮助,但除了主线程外,我只使用一个子线程;使用AsyncTask扫描4到5个小时,CPU速度会上升到很高 – Victor
[应用程序CPU使用率在android中是否很高?](http://*.com/questions/14688222/application-cpu-usage-is-high-in-android) –