【java基础】多线程匿名内部类和lambda创建方式,及多线程中的两个面试题 2017年10月25日 22:47:09

2017年10月25日 22:47:09

一、可以用匿名类和lambda两个种方式创建多线程。

1.利用匿名内部类创建多线程并开启。

[java]  view plain  copy
  1. new Thread() {//创建方式1  
  2.     public void run() {  
  3.         for(int x=0; x<50; x++) {          
  4.             System.out.println(Thread.currentThread().getName()+"....x="+x);  
  5.         }  
  6.     }  
  7. }.start();  
  8.   
  9. Runnable r = new Runnable() {//创建方式2  
  10.     public void run() {   
  11.         for(int x=0; x<50; x++) {          
  12.             System.out.println(Thread.currentThread().getName()+"....z="+x);  
  13.         }  
  14.     }  
  15. };  
  16. new Thread(r).start();  


2.利用lambda方式创建多线程并开启。

[java]  view plain  copy
  1. Runnable r = ()->{  
  2.     for(int x=0; x<50; x++){  
  3.         System.out.println(Thread.currentThread().getName()+"....z="+x);  
  4.     }  
  5. };  
  6. new Thread(r).start();  
二、两个面试题

1.第一题

[java]  view plain  copy
  1. class Test implements Runnable  
  2. {  
  3.     public void run(Thread t)  
  4.     {}  
  5. }  
  6. //如果错误 错误发生在哪一行?  
  7. //答案:错误在第一行,应该被abstract修饰,因为run()抽象方法没有被重写。  

2.第二题
[java]  view plain  copy
  1. class ThreadTest   
  2. {  
  3.     public static void main(String[] args)   
  4.     {  
  5.   
  6.         new Thread(new Runnable()  
  7.         {  
  8.             public void run()  
  9.             {  
  10.                 System.out.println("runnable run");  
  11.             }  
  12.         })  
  13.         {  
  14.             public void run()  
  15.             {  
  16.                 System.out.println("subThread run");  
  17.             }  
  18.         }.start();  
  19.     }  
  20. }  
问题:在Thread方法中引入了一个多线程任务的参数,该参数重写了run()方式,同时又用匿名内部类的方式重写了run()方法。问,将会输出哪个?

答案:将会输出subThread run,必须以子类为主,若子类没有,在输出参数任务中的runnable run,若都没有,则执行Thread类中默认的run()方法。

猜你喜欢

转载自blog.csdn.net/xyajia/article/details/80453810
今日推荐