创建线程池的方法:
ExecutorService mFixedExecutor = Executors.newFixedThreadPool(2);
以上newFixedThreadPool内部有个任务队列,假设线程池里有2个线程,提交了5个任务,
那么后三个任务就放在任务队列了,即使前2个任务sleep或者堵塞了,也不会执行后三个任务,除非前两个任务有执行完的。
实例1:
public class ExecutorServiceTest { public static void main(String[] args) throws IOException, InterruptedException { // 创建一个固定大小的线程池 ExecutorService service = Executors.newFixedThreadPool(3); for (int i = 0; i < 10; i++) { System.out.println("创建线程" + i); Runnable run = new Runnable() { @Override public void run() { System.out.println("启动线程"); } }; // 在未来某个时间执行给定的命令 service.execute(run); } // 关闭启动线程 service.shutdown(); // 等待子线程结束,再继续执行下面的代码 service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); System.out.println("all thread complete"); } }
实例2:
public class ThreadTest extends Activity{ private static final int POOL_SIZE = 2; private static ExecutorService mFixedExecutor; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_threadtest); //创建一个两个大小的线程池 mFixedExecutor = Executors.newFixedThreadPool(POOL_SIZE); findViewById(R.id.button1).setOnClickListener(new OnClickListener() { public void onClick(View v) { //创建执行任务 Runnable td=new ThreadDemo(); //把任务添加到Thread线程的构造参数中。 Thread th1=new Thread(td); Thread th2=new Thread(td); Thread th3=new Thread(td); Thread th4=new Thread(td); Thread th5=new Thread(td); Thread th6=new Thread(td); Thread th7=new Thread(td); Thread th8=new Thread(td); Thread th9=new Thread(td); Thread th10=new Thread(td); //把Thread的线程,添加到线程池中。 mFixedExecutor.execute(th1); mFixedExecutor.execute(th2); mFixedExecutor.execute(th3); mFixedExecutor.execute(th4); mFixedExecutor.execute(th5); mFixedExecutor.execute(th6); mFixedExecutor.execute(th7); mFixedExecutor.execute(th8); mFixedExecutor.execute(th9); mFixedExecutor.execute(th10); } }); } class ThreadDemo implements Runnable { int id=10; Object obj=new Object(); // public synchronized void run()同步的意思 如果不需要同步,就把synchronized去掉 public void run(){ /* 当第一个线程执行到这个位置时,有可能让当前线程改变成 临时堵塞状态,而第二个线程变成运行状态。 如果这种情况出现,结果是多少? */ //人为让当前正在执行的线程释放执行权 try{ Thread.sleep(2000); //释放执行权,没有释放锁. }catch(Exception e){ } Log.e("ThreadTest", id+++""+Thread.currentThread().getName()); } } }