我有一个按钮,当点击时调用一个启动线程的方法。但那个线程有止损,很好。我希望首先完成线程,然后执行其余的代码。
我尝试使用wait()但没有工作。
public void configure(Button arg0,TextView arg1) throws InterruptedException{
//calling OpenDeviceListener
readText=arg1;
button= arg0;
//handler
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.d("Handler","running");
if (actualNumBytes != 0x00) {
Log.d("handler","if");
readText.append(String.copyValueOf(readBuffer, 0,
actualNumBytes));
Log.d("handler","if 312");
actualNumBytes = 0;
Log.d("handler","if end");
}
Log.d("handler","closed");
}
};
Log.d("163","tab");
uartInterface = new CH34xAndroidDriver(
(UsbManager) getSystemService(Context.USB_SERVICE), this,
ACTION_USB_PERMISSION);
Log.d("167","tab");
act_string = getIntent().getAction();
if(-1 != act_string.indexOf("android.intent.action.MAIN"))
{
Log.d(TAG, "android.intent.action.MAIN 171");
}
else if(-1 != act_string.indexOf("android.hardware.usb.action.USB_DEVICE_ATTACHED"))
{
Log.d(TAG, "android.hardware.usb.action.USB_DEVICE_ATTACHED 175");
}
if(!uartInterface.UsbFeatureSupported())
{
Toast.makeText(this, "No Support USB host API", Toast.LENGTH_SHORT).show();
Log.d("182","tab");
readText.setText("No Support USB host API");
Log.d("184","tab");
uartInterface = null;
}
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
if(READ_ENABLE == false) {
READ_ENABLE = true;
Log.d("192","tab");
handlerThread = new readThread(handler);
handlerThread.start();
}
Log.d("192","End");
try{
this.wait(100);
}
catch(InterruptedException e){
e.printStackTrace();
Log.d("Exception",e.getMessage());
}
// TODO Auto-generated method stub
Log.d("205","OpenDeviceListener");
boolean flags;
if(false == isConfiged) {
Log.d("209","OpenDeviceListener");
Toast.makeText(global_context,""+((Boolean)uartInterface.isConnected()), Toast.LENGTH_LONG).show();
isConfiged = true;
// writeButton.setEnabled(true);
if(uartInterface.isConnected()) {
Toast.makeText(global_context,""+(Boolean)uartInterface.isConnected(), Toast.LENGTH_SHORT).show();
Log.d("213","OpenDeviceListener");
flags = uartInterface.UartInit();
if(!flags) {
Log.d(TAG, "Init Uart Error 2");
Toast.makeText(global_context, "Init Uart Error", Toast.LENGTH_SHORT).show();
} else {
if(uartInterface.SetConfig(baudRate, dataBit, stopBit, parity, flowControl)) {
Log.d(TAG, "Configed");
}
}
}
}
}
并且plz清除了一个事情,就是线程没有调用stop(),直到线程运行。 感谢
答案 0 :(得分:0)
final Runnable runnable = new Runnable() {
@Override
public void run() {
//this method will be called after 2 seconds
//do your task here
}
};
final Handler h = new Handler();
h.removeCallbacks(runnable); // cancel the running action (the
// hiding process)
h.postDelayed(runnable, 2000);
答案 1 :(得分:0)
试试这个:
Object lock = new Object;
synchronized(lock){
lock.wait();
}
这将阻止运行这些代码的当前线程。 当它的时间通知被阻止的代码
synchronized (lock) {
lock.notify();
}
如果只想让线程在特定时间内休眠,为什么不使用
Thread.sleep(1000);