1、小型系统
// 线程完成的任务(Runnable对象)和线程对象(Thread)之间紧密相连 class A implements Runnable{ public void run(){ // 业务逻辑 } } for ( int i =0;i<10;i++){ Thread t = new Thread(new A()); t.setName("Thread-"+i); t.start(); }
2、大型系统
/** 1、线程管理和创建工作与应用程序的其余部分分离开 2、封装线程管理和创建的对象被成为执行器(Executor) 3、jdk中定义了3个执行器接口:Executor,ExecutorService和ScheduledExecutorService 4、常用的线程池(优劣参见“阿里代码规约”): FixedThreadPool、 SingleThreadExecutor、 CachedThreadPool、 ScheduledThreadPool **/ class A implements Runnable{ public void run(){ } } // 示例 ThreadFactory tf = new ThreadFactoryBuilder().setNameFormat("Thread-%d").build(); ExecutorService es = new ThreadPoolExecutor(5,10,0L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(1024),tf,new ThreadPoolExecutor.AbortPolicy); es.execute(new A());// 该操作可放在循环中模拟并发 es.shutdown();
3、