publicsynchronizedvoidbow(Friend friend){ System.out.format("%s:%s" + " has bowed to me!%n", this.name, friend.getName()); friend.bowBack(this); } publicsynchronizedvoidbowBack(Friend friend){ System.out.format("%s:%s" + " has bowed back to me!%n", this.name, friend.getName()); } }
publicstaticvoidmain(String[] args)throws InterruptedException { final Friend friendA = new Friend("Shuai"); final Friend friendB = new Friend("Junlan"); ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 2, 1000L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(2)); /// Why not using this way to create ThreadPool? // ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2); threadPoolExecutor.execute(() -> friendA.bow(friendB)); threadPoolExecutor.execute(() -> friendB.bow(friendA)); threadPoolExecutor.shutdown();
} }
output
1 2
Shuai:Junlan has bowed to me! Junlan:Shuai has bowed to me!