Java线程池
- - 企业架构 - ITeye博客线程的使用在java中占有极其重要的地位,在jdk1.4极其之前的jdk版本中,关于线程池的使用是极其简陋的. 在jdk1.5之后这一情况有了很大的改观. Jdk1.5之后加入了java.util.concurrent包,这个包中主要介绍java中线程以及线程池的使用. 为我们在开发中处理线程的问题提供了非常大的帮助.
package org.thread; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class PrimeGenerator extends Thread { private final List<BigInteger> primes=new ArrayList<BigInteger>(); private volatile boolean cancelled; @Override public void run() { // TODO Auto-generated method stub BigInteger p=BigInteger.ONE; while(!cancelled){ try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } p=p.nextProbablePrime(); synchronized (this) { primes.add(p); } } } public void cancell(){cancelled=true;}; public synchronized List<BigInteger> get(){ return new ArrayList<BigInteger>(primes); } }
package org.thread; public class InterruptTest { public static void main(String[] args) { PrimeGenerator t=new PrimeGenerator(); // PrimeGenerator1 t=new PrimeGenerator1(); t.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } t.cancell(); long start=System.currentTimeMillis(); long end=0; while(t.isAlive()){ end=System.currentTimeMillis(); } System.out.println(end-start); } }
package org.thread; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class PrimeGenerator1 extends Thread{ private final List<BigInteger> primes=new ArrayList<BigInteger>(); @Override public void run() { // TODO Auto-generated method stub BigInteger p=BigInteger.ONE; while(!Thread.currentThread().isInterrupted()){ try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block Thread.currentThread().interrupt(); e.printStackTrace(); } p=p.nextProbablePrime(); synchronized (this) { primes.add(p); } } } public void cancell(){interrupt();}; public synchronized List<BigInteger> get(){ return new ArrayList<BigInteger>(primes); } }
package org.thread; public class InterruptTest { public static void main(String[] args) { // PrimeGenerator t=new PrimeGenerator(); PrimeGenerator1 t=new PrimeGenerator1(); t.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } t.cancell(); long start=System.currentTimeMillis(); long end=0; while(t.isAlive()){ end=System.currentTimeMillis(); } System.out.println(end-start); } }