接口继承的写法1:在类名后写上继承的接口,然后在类的内部重写方法
示例:
1 class Consumer implements Runnable{ 2 3 private BlockingQueue<Integer> queue; 4 5 public Consumer(BlockingQueue<Integer> queue){ 6 this.queue = queue; 7 } 8 9 @Override 10 public void run() { 11 try { 12 while (true) { 13 Thread.sleep(new Random().nextInt(1000)); 14 queue.take(); 15 System.out.println(Thread.currentThread().getName()+"消费"+queue.size()); 16 } 17 } catch (InterruptedException e) { 18 e.printStackTrace(); 19 } 20 } 21 }
接口继承的写法2:直接new 一个接口类型的对象,再使用匿名内部类的方式重写方法
示例:
1 // 1.JDK普通线程池 2 @Test 3 public void testExecutorService() { 4 Runnable task = new Runnable() {//实现Runnable接口,这里是匿名实现,方法中写要执行的方法 5 @Override 6 public void run() { 7 System.out.println("Hello ExecutorService"); 8 // logger.debug("Hello ExecutorService"); 9 } 10 }; 11 12 for (int i = 0; i < 10; i++) { 13 executorService.submit(task);//提交任务给线程池,就会安排线程处理 14 } 15 16 sleep(10000); 17 } 18 19 //Test中的线程执行完了就会结束,不会等一下看话有没有任务,因此需要定义一个sleep方法让这些线程等一下 20 private void sleep(long m) {//sleep方法经常抛异常,封装一下,处理一下异常 21 try { 22 Thread.sleep(m); 23 } catch (InterruptedException e) { 24 e.printStackTrace(); 25 } 26 }