0

我的一个线程正在创建另一个线程以在特定时间间隔内执行某些操作。它是通过计时器来完成的。

现在当原始线程停止时,另一个线程仍在运行,我无法让它停止。

如何正确终止“线程”?:

Thread thread = new Thread() {

    @Override
    public void run() {
        try {
            while (true) {
                sleep(1000);
                // do something
            }
        } catch (InterruptedException e) {
            Log.e(TAG,"new invoked caught the exception!");
            return;
        }
    }
};

public void run() {
    while (true) {
        try {
            Log.d(TAG,"ConnectedThread.run: Reading from InStream socket");
            while (true) {
                thread.start();
                Log.e(TAG,"starting additional thread");
                // Read from the InputStream
                int inB;
                inB = mmInStream.read();
                if (inB != -1) mAccessoryInfo.addCharacter((byte) inB);
            }
        } catch (IOException e) {
            Log.e(TAG, "TADA InStream read exception, disconnected "
                    + e.getMessage());
            // stopService(new Intent(getBaseContext(), Pinger.class));
            thread = null;
            connectionLost();
            break;
        }
    }
}
4

5 回答 5

1
Hi thread is stop by kill() or stop() or destroy method of thread but this all are              
deprecated so dont kill the thread thread is automatically destroy after done its work.   
 so   
if you want to do any work use handler like this not thread in therad.
new Thread() {

        public void run() {

            try {
                Message msg = new Message();
                msg.arg2 = 0;
                handle.sendMessage(msg);
                Thread.sleep(5000);
            } catch (Exception e) {
                Log.e("tag", e.getMessage());
            }

            //

        }

    }.start();
 and make handler in ur activity like this
 public static Handler handle = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        if (msg.arg2 == 0) {
            Toast.makeText(context, "No data to sync.",    
  Toast.LENGTH_SHORT)
                    .show();
        } else if (msg.arg2 == 1) {
            Toast.makeText(context, "Data Sync Completed.",
                    Toast.LENGTH_SHORT).show();

        } else {
            Toast.makeText(context, "Data Sync not Completed.",
                    Toast.LENGTH_SHORT).show();
        }

    }
};
于 2013-03-06T05:35:03.390 回答
0

你会想要中断线程。“正常”的事情是更改while(true)to while(!isInterrupted),但是当您在 while 循环上方捕获该异常时,它会在您中断它时进入 catch 块。您可以通过调用来中断线程thread.interrupt()

于 2013-03-06T04:52:35.623 回答
0

根据您愿意做什么,也许您想要一个或多个处理程序/循环器线程。

Looper 文档http://developer.android.com/reference/android/os/Looper.html和 Handler 类 http://developer.android.com/reference/android/os/Handler中给出了代码示例.html 提供了您可能使用的方法(如 postAtTime())。

于 2013-03-06T05:09:49.997 回答
0

当您说您有一个“线程”启动另一个“线程”时,我有点困惑,您的意思是一个Activity正在启动一个线程并且它正在Activity被销毁并让一个孤立线程运行吗?如果是这种情况,那么我会请求关闭该Activity's onDestroy()方法中的线程。

onDestroy()

  ...
  if(yourThread != null){
    yourThread.interrupt();
  }
  ...

但我会有点担心使用这样的计时器,没有其他方法可以实现您的目标吗?即,异步任务和使用任务何时开始/完成的标志

于 2013-03-06T05:11:23.167 回答
0

只需在 java util 并发框架中使用可调用语句。

父线程代码将像

public class Worker implements Callable<Boolean>
{
    @Override
    public Boolean call() throws Exception 
    { 
        //Your worker code here
    }
}

void callingmethod()
{
    //Three threads executing upon five worker modules.

    ExecutorService executor = Executors.newFixedThreadPool(3); 

    List<Worker> list = new ArrayList<Worker>(5);  //For example 5 workers.

    for(int i=0; i<5; i++)
    {
        list.add(new Worker());
    }

    List<Future<Boolean>> futures = executor.invokeAll(list);

    for(Future<Boolean> future : futures)
    {
    future.get();
    }

    executor.shutdown();

    executor.awaitTermination(5, TimeUnit.SECONDS);
}

语句 future.get 意味着,运行调用方法的线程将阻塞,直到所有工作人员在执行工作后返回。

于 2013-03-06T05:15:23.120 回答