美文网首页程序员
java线程状态和线程池

java线程状态和线程池

作者: 万万_936b | 来源:发表于2019-04-19 14:23 被阅读6次

    本节总结线程相关知识:线程状态和线程池。
    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

    相关文章

      网友评论

        本文标题:java线程状态和线程池

        本文链接:https://www.haomeiwen.com/subject/fpvqgqtx.html