程序员

java线程状态和线程池

2019-04-19  本文已影响6人  万万_936b

本节总结线程相关知识:线程状态和线程池。
1.线程的五个状态


线程.png

关于如何终止线程,以下仅供参考:

线程:
public class ThreadTest extends Thread {
    @Override
    public void run() {
        try {
            Log.d("ThreadTest", Thread.currentThread().getName() + "线程开始");
            for (int i = 0; i < 10000; i++) {
                if (this.isInterrupted()) {
                    Log.d("ThreadTest", "i循环停止:" + i);
                    throw new InterruptedException();
                }
                Log.d("ThreadTest", "i:" + i);
            }

            for (int j = 0; j < 10000; j++) {
                if (this.isInterrupted()) {
                    Log.d("ThreadTest", "j循环停止:" + j);
                    throw new InterruptedException();
                }
                Log.d("ThreadTest", "j:" + j);
            }
        } catch (InterruptedException e) {
            Log.d("ThreadTest", Thread.currentThread().getName() + "线程停止");
            Log.d("ThreadTest", "InterruptedException:" + e.getMessage());
        }
    }
}
测试:
try {
        ThreadTest threadTest = new ThreadTest();
        threadTest.start();
        Log.d("ThreadTest", "getName:" + threadTest.getName());
        Thread.sleep(2000);
        Log.d("ThreadTest", "isInterrupted1:" + threadTest.isInterrupted());
        threadTest.interrupt();
        Log.d("ThreadTest", "isInterrupted2:" + threadTest.isInterrupted());
    } catch (InterruptedException e) {
        Log.d("ThreadTest", "InterruptedException:" + e.getMessage());
    }
结果:
ThreadTest: j:2849
ThreadTest: j:2850
ThreadTest: j:2851
ThreadTest: isInterrupted1:false
ThreadTest: j:2852
ThreadTest: isInterrupted2:true
ThreadTest: j循环停止:2853
ThreadTest: Thread-9577线程停止
Choreographer: Skipped 121 frames!  The application may be doing too much work on its main thread.
ThreadTest: InterruptedException:null

2.线程池


线程池.png
上一篇 下一篇

猜你喜欢

热点阅读