其他分享
首页 > 其他分享> > 线程池ThreadPoolExecutor

线程池ThreadPoolExecutor

作者:互联网

开启三个核心线程,一共五个线程,任务过多就启用另两个线程,如果还不够用,就会任务等待,或抛出异常,

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3,5,1, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(100));

        for(int i = 0;i<30;i++){
            final int finali = i;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                        Log.d("Thread", "run: "+finali);
                        Log.d("当前线程:",Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            threadPoolExecutor.execute(runnable);
        }
    }
}

 

标签:setContentView,savedInstanceState,线程,new,onCreate,ThreadPoolExecutor
来源: https://www.cnblogs.com/Ocean123123/p/10969565.html