publicclassTaskimplementsRunnable{ //存储任务的创建时间 private Date initDate;
//存储任务的名称 private String name;
publicTask(String name){ initDate = new Date(); this.name = name; }
@Override publicvoidrun(){ //创建时间 System.out.printf("%s: Task %s: Created on: %s\n", Thread.currentThread().getName(), name, initDate); //开始时间 System.out.printf("%s: Task %s: Started on: %s\n",Thread.currentThread().getName(),name,new Date());
try{ Long duration = (long)(Math.random() * 10); System.out.printf("%s: Task %s: Doing a task during %d seconds\n", Thread.currentThread().getName(), name, duration); TimeUnit.SECONDS.sleep(duration); }catch(InterruptedException e){ e.printStackTrace(); } //结束时间 System.out.printf("%s: Task %s: Finished on: %s\n", Thread.currentThread().getName(), name, new Date()); }
publicvoidexecuteTask(Task task){ System.out.printf("Server: A new task has arrived\n"); executor.execute(task); System.out.printf("Server: Pool Size: %d\n",executor.getPoolSize()); System.out.printf("Server: Active Count: %d\n",executor.getActiveCount()); System.out.printf("Server: Completed Tasks: %d\n",executor.getCompletedTaskCount()); }
publicvoidendServer(){ executor.shutdown(); } }
主类
1 2 3 4 5 6 7 8 9 10
publicclassMain{ publicstaticvoidmain(String[] args){ Server server = new Server(); for(int i = 0; i < 100; i++){ Task task = new Task("Task " + i); server.executeTask(task); } server.endServer(); } }
publicclassTaskimplementsRunnable{ private Date initDate; private String name;
publicTask(String name){ initDate = new Date(); this.name = name; }
@Override publicvoidrun(){ System.out.printf("%s: Task %s : Created on: %s\n", Thread.currentThread().getName(), name, initDate); System.out.printf("%s: Task %s: Started on: %s\n", Thread.currentThread().getName(), name, new Date());
try{ Long duration = (long)(Math.random() * 10); System.out.printf("%s: Task %s: Doing a task during %d seconds\n", Thread.currentThread().getName(), name, duration); TimeUnit.SECONDS.sleep(duration); }catch(InterruptedException e){ e.printStackTrace(); }
System.out.printf("%s: Task %s: Finished on: %s\n", Thread.currentThread().getName(), new Date(), name); } }
主类
1 2 3 4 5 6 7 8 9 10
publicclassMain{ publicstaticvoidmain(String[] args){ Server server = new Server(); for(int i = 0; i < 100; i++){ Task task = new Task("Task " + i); server.executeTask(task); } server.endServer(); } }
publicclassMain{ publicstaticvoidmain(String[] args){ ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2); //创建一个Future<Integer>类型的列表对象resultList List<Future<Integer>> resultList = new ArrayList<>(); Random random = new Random(); for(int i = 0; i < 10; i++){ Integer number = new Integer(random.nextInt(10)); FactorialCalculator calculator = new FactorialCalculator(number); Future<Integer> result = executor.submit(calculator); resultList.add(result); }
do{ //任务完成的数量 System.out.printf("Main: Number of Completed Tasks: %d\n",executor.getCompletedTaskCount()); //遍历10个Future对象,通过isDone()输出任务是否完成 for(int i = 0;i < resultList.size(); i++){ Future<Integer> result = resultList.get(i); System.out.printf("Main: Task %d: %s\n", result.isDone()); } try{ Thread.sleep(50); }catch(InterruptedException e){ e.printStackTrace(); } }while(executor.getCompletedTaskCount()<resultList.size()); System.out.printf("Main: Results\n"); for(int i = 0 ; i < resultList.size(); i++){ Future<Integer> result = resultList.get(i); Integer number = null; try{ number = result.get(); }catch(InterruptedException e){ e.printStackTrace(); }catch(ExecutionException e){ e.printStackTrace(); } System.out.printf("Core: Task %d: %d\n",i,number); } executor.shutdown(); } }
@Override public String call()throws Exception{ if(!validator.validate(user, password)){ //如果用户没有通过UserValidator验证,抛出Exception System.out.printf("%s: The user has not been found\n",validator.getName()); thrownew Exception("Error validating user"); } System.out.printf("%s: The user has been found\n",validator.getName()); return validator.getName(); } }
@Override public Result call()throws Exception{ System.out.printf("%s: Staring\n", this.name);
try{ Long duration = (long)(Math.random()*10); System.out.printf("%s: Waiting %d seconds for results.\n", this.name,duration); TimeUnit.SECONDS.sleep(duration); }catch(InterruptedException e){ e.printStackTrace(); } int value = 0; for(int i = 0; i < 5; i++){ value += (int)(Math.random()*100); }
Result result = new Result(); result.setName(this.name); result.setValue(value); System.out.printf("%s: Ends\n", this.name);
Task task = new Task("Task"); ScheduledFuture<?> result = executor.scheduleAtFixedRate(task, 1, 2, TimeUnit.SECONDS);
for(int i = 0; i < 10; i++){ System.out.printf("Main: Delay: %d\n", result.getDelay(TimeUnit.MILLISECONDS)); try{ TimeUnit.MILLISECONDS.sleep(500); }catch(InterruptedException e){ e.printStackTrace(); } }
executor.shutdown(); System.out.printf("Main: No More tasks at: %s\n", new Date()); try{ TimeUnit.SECONDS.sleep(5); }catch(InterruptedException e){ e.printStackTrace(); }
System.out.printf("Main: Finished at: %s\n", new Date()); }
@Override protectedvoiddone(){ if(isCancelled()){ System.out.printf("%s: Has been cancelled\n",name); }else{ System.out.printf("%s: Has finished\n",name); } } }
@Override publicvoidrun(){ System.out.printf("%s: Going to print a job\n",Thread.currentThread().getName()); printQueue.printJob(new Object()); System.out.printf("%s: The document has been printed\n", Thread.currentThread().getName()); } }
主类
1 2 3 4 5 6 7 8 9 10
publicclassMain{ publicstaticvoidmain(String[] args){ PrintQueue printQueue = new PrintQueue();
Thread thread[] = new Thread[10]; for(int i = 0; i < 10; i++){ thread[i] = new Thread(new Job(printQueue),"Thread " + i); } } }
publicPrintQueue(){ semaphore = new Semaphore(3); freePrinters = newboolean[3]; for(int i = 0; i < 3; i++){ freePrinters[i] = true; } lockPrinters = new ReentrantLock(); }
publicvoidprintJob(Object document){ try{ semaphore.acquire(); int assignedPrinter = getPrinter(); Long duration = (long)(Math.random()*10); System.out.printf("%s: PrintQueue: Printing a Job in Printer %d during %d seconds\n",Thread.currentThread().getName(),assignedPrinter,duration); TimeUnit.SECONDS.sleep(duration);
@Override publicvoidrun(){ System.out.printf("%s: Going to print a job\n",Thread.currentThread().getName()); printQueue.printJob(new Object()); System.out.printf("%s: The document has been printed\n",Thread.currentThread().getName()); } }
主类
1 2 3 4 5 6 7 8 9 10 11 12
publicclassMain{ publicstaticvoidmain(String[] args){ PrintQueue printQueue = new PrintQueue(); Thread thread[] = new Thread[12]; for(int i = 0; i < 12; i++){ thread[i] = new Thread(new Job(printQueue), "Thread " + i); } for(int i = 0;i < 12; i++){ thread[i].start(); } } }
publicclassMain{ publicstaticvoidmain(String[] args){ Phaser phaser = new Phaser(3);
FileSearch system = new FileSearch("C:\\XXX", "log", phaser); FileSearch apps = new FileSearch("C:\\XXXX", "log", phaser); FileSearch documents = new FileSearch("C:\\XXXXX","log", phaser);
Thread systemThread = new Thread(system, "System"); systemThread.start();
Thread appsThread = new Thread(apps, "Apps"); appsThread.start();
Thread documentsThread = new Thread(documents, "Documents"); documentsThread.start();
publicclassMyPhaserextendsPhaser{ @Override protectedbooleanonAdvance(int phase, int registeredParties){ switch(phase){ case0: return studentsArrived();
case1: return finishFirstExercise();
case2: return finishSecondExercise();
case3: return finishExam();
default: returntrue; } }
privatebooleanstudentsArrived(){ System.out.printf("Phaser: The exam are going to start. The students are ready.\n"); System.out.printf("Phaser: We have %d students.\n",getRegisteredParties()); returnfalse; }
privatebooleanfinishFirstExercise(){ System.out.printf("Phaser: All the students has finished the first exercise.\n"); System.out.printf("Phaser: It's turn for the second one.\n"); returnfalse; }
privatebooleanfinishSecondExercise(){ System.out.printf("Phaser: All the students has finished the second exercise.\n"); System.out.printf("Phaser: It's turn for the third one.\n"); returnfalse; }
privatebooleanfinishExam(){ System.out.printf("Phaser: All the students has finished the exam.\n"); System.out.printf("Phaser: Thank you for your time.\n"); returntrue; }
publicvoidrun(){ System.out.printf("%s: Has arrived to do the exam. %s\n",Thread.currentThread().getName(),new Date()); phaser.arriveAndAwaitAdvance(); System.out.printf("%s: Is going to do the first exercise. %s\n",Thread.currentThread().getName(),new Date()); doExercise1();
System.out.printf("%s: Has done the first exercise. %s\n",Thread.currentThread().getName(),new Date()); phaser.arriveAndAwaitAdvance(); System.out.printf("%s: Is going to do the second exercise. %s\n",Thread.currentThread().getName(),new Date()); doExercise2();
System.out.printf("%s: Has done the second exercise. %s\n",Thread.currentThread().getName(),new Date()); phaser.arriveAndAwaitAdvance(); System.out.printf("%s: Is going to do the third exercise. %s\n",Thread.currentThread().getName(),new Date()); doExercise3(); System.out.printf("%s: Has finished the exam. %s\n",Thread.currentThread().getName(),new Date()); phaser.arriveAndAwaitAdvance(); }
Exchanger类还提供了另外的exchanger方法,即exchange(V data, long time, TimeUnit unit)方法。 V指要交换的数据结构 time指定等待的time值 TimeUnit可以是DAYS\HOURS\MICROSECONDS\MILLISECONDS\MINUTES\NANOSECONDS\SECONDS
@Override publicvoidrun(){ System.out.printf("%s: Going to print a document\n",Thread.currentThread().getName()); printQueue.printJob(new Object()); System.out.printf("%s: The document has been printed\n",Thread.currentThread().getName()); } }
主类
1 2 3 4 5 6 7 8 9 10 11 12 13 14
public class Main(){ publicstaticvoidmain(String[] args){ PrintQueue printQueue = new PrintQueue();
Thread thread[] = new Thread[10]; for(int i = 0; i < 10; i++){ thread[i] = new Thread(new Job(printQueue), "Thread " + i); }
for(int i = 0; i < 10; i++){ thread[i].start(); } } }
@Override publicvoidrun(){ while(buffer.hasPendingLines()){ String line = buffer.get(); processLine(line); } }
privatevoidprocessLine(String line){ try{ Random random = new Random(); Thread.sleep(random.nextInt(100)); }catch(InterruptedException e){ e.printStackTrace(); } } }
@Override publicvoiduncaughtException(Thread t, Throwable e){ System.out.printf("The thread %s has thrown an Exception\n",t.getId()); e.printStackTrace(System.out); System.out.printf("Terminating the rest of the Threads\n"); interrupt(); } }
创建Task类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
publicclassTaskimplementsRunnable{ @Override publicvoidrun(){ int result; Random random=new Random(Thread.currentThread().getId()); while (true) { result=1000/((int)(random.nextDouble()*1000)); System.out.printf("%s : %f\n",Thread.currentThread().getId(),result); if (Thread.currentThread().isInterrupted()) { System.out.printf("%d : Interrupted\n",Thread.currentThread().getId()); return; } } } }