0

私のスレッドの 1 つは、特定の間隔で何かを行うために別のスレッドを作成しています。これはタイマーによって行われます。

元のスレッドが停止しても、他のスレッドはまだ実行中であり、停止させることはできません。

「スレッド」を適切に終了するにはどうすればよいですか?:

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)ですwhile(!isInterrupted)が、whileループの上でその例外をキャッチしているため、中断するとキャッチブロックに移動します。を呼び出してスレッドを中断できますthread.interrupt()

于 2013-03-06T04:52:35.623 に答える
0

やりたいことに応じて、1 つ以上のハンドラー/ルーパー スレッドが必要になる場合があります。

コード例は、ルーパー ドキュメント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 に答える