【java基础】多线程匿名内部类和lambda创建方式,及多线程中的两个面试题

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()方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值