Java Gossip: Executors
有时候您需要建立一堆Thread来执行一些小任务,然而频繁的建立Thread有时会是个开销,因为Thread的建立必须与作业系统互动,如果能建立一个Thread pool来管理这些小的Thread并加以重复使用,对于系统效能会是个改善的方式。 您可以使用Executors来建立Thread pool,Executors有几个static方法,列出如下:
举个简单的实例,下面的程式使用newFixedThreadPool方法建立Thread pool,当中包括五个可以重复使用的Thread,您可以指定Runnable物件给它,程式中会产生十个Runnable物件,由于Thread pool中只有五个可用的Thread,所以后来建立的五个Runnable必须等待有空闲的Thread才会被执行:
package onlyfun.caterpillar; submit()方法也接受实作Callable介面的物件,最后传回Future物件,可以取得Callable执行过后的传回结果。 如果想利用Executors进行排程,例如排定某个工作30秒后执行: ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor( ); scheduler.schedule(new Runnable( ) { public void run() { // 排程工作 } }, 30, TimeUnit.SECONDS); 或排定某个工作5秒后执行,之后每30秒执行一次: ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor( ); final ScheduledFuture future = scheduler.scheduleAtFixedRate(new Runnable( ) { public void run() { // 排程工作 System.out.println("t"); } }, 0, 5, TimeUnit.SECONDS); // 排定 60 秒后取消future scheduler.schedule(new Runnable( ) { public void run( ) { future.cancel(false); } }, 60, TimeUnit.SECONDS); 如上所示,想要取消排程任务,可以呼叫ScheduledFuture的cancel()方法。 | <script type="text/javascript">
</script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script> name="google_ads_frame" marginwidth="0" marginheight="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-9750319131714390&dt=1197007384156&lmt=1181153050&format=160x600_as&output=html&correlator=1197007384109&url=http%3A%2F%2Fcaterpillar.onlyfun.net%2FGossipCN%2FJavaGossip-V2%2FExcutors.htm&ad_type=text_image&ref=http%3A%2F%2Fwww.baidu.com%2Fs%3Fie%3Dgb2312%26bs%3DExecutorService%26sr%3D%26z%3D%26cl%3D3%26f%3D8%26wd%3DExecutors%26ct%3D0&cc=384&ga_vid=1519114475.1197007384&ga_sid=1197007384&ga_hid=1360029615&flash=9&u_h=768&u_w=1024&u_ah=738&u_aw=1024&u_cd=32&u_tz=480&u_java=true" frameborder="0" width="160" scrolling="no" height="600" allowtransparency="allowtransparency"> <script type="text/javascript"> </script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script> name="google_ads_frame" marginwidth="0" marginheight="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-9750319131714390&dt=1197007384187&lmt=1181153050&prev_fmts=160x600_as&format=160x600_as&output=html&correlator=1197007384187&url=http%3A%2F%2Fcaterpillar.onlyfun.net%2FGossipCN%2FJavaGossip-V2%2FExcutors.htm&ad_type=text_image&ref=http%3A%2F%2Fwww.baidu.com%2Fs%3Fie%3Dgb2312%26bs%3DExecutorService%26sr%3D%26z%3D%26cl%3D3%26f%3D8%26wd%3DExecutors%26ct%3D0&cc=384&ga_vid=1519114475.1197007384&ga_sid=1197007384&ga_hid=1360029615&flash=9&u_h=768&u_w=1024&u_ah=738&u_aw=1024&u_cd=32&u_tz=480&u_java=true" frameborder="0" width="160" scrolling="no" height="600" allowtransparency="allowtransparency"> |