Part1.java
//餓漢式的單例模式 public class Singleton { private static Singleton instance; static{ instance = new Singleton(); } private Singleton(){ //消耗資源的操做 } public static Singleton getInstance(){ return instance; } }
//Future模式 public class TestFuture { static class Job<Object> implements Callable<Object>{ @Override public Object call() throws Exception { return loadData(); //執行時間可能較長 } private Object loadData() { return null; } } public static void main(String[] args) throws Exception{ FutureTask future = new FutureTask(new Job<Object>()); new Thread(future).start(); // do something else Object result = future.get(); } }
//設置固定大小爲5的線程池,用它來併發執行1000個任務 public class TestExecutorService { static class Job implements Runnable{ @Override public void run() { doWork(); } private void doWork() { System.out.println("doing..."); } } public static void main(String[] args){ ExecutorService exec = Executors.newFixedThreadPool(5); for(int i=0; i<1000; i++){ exec.execute(new Job()); } } }
Part2.併發
Part3.ide