java多线程——简化线程使用以及lambda快速入门
简化线程的使用
1、静态内部类
class MyThread{ static class test implements Runnable{ public void run(){ for(int i=0;i<10;i++){ System.out.println("学习_(:з」∠)_"); } } } public static void main(String[] args){ new Thread(new test()).start(); } }
运行结果
对于只使用一次的,可以使用内部类加快运行速率,它的特点是,只有使用时才会进行编译,且内部类的引用更快。
2、方法中的类(局部内部类)
class MyThread{ public static void main(String[] args){ class test implements Runnable{ public void run(){ for(int i=0;i<10;i++){ System.out.println("学习_(:з」∠)_"); } } } new Thread(new test()).start(); } }
将内部类移动到方法里面
3、匿名内部类
需要借助接口或者是父类
class MyThread{ public static void main(String[] args){ new Thread(new Runnable() { @Override public void run() { for(int i=0;i<10;i++){ System.out.println("学习(≧∇≦)ノ"); } } }).start(); } }
运行结果
只针对较为简单的方法
4、匿名内部类,且简化run方法
实例:
class MyThread{ public static void main(String[] args){ new Thread(()->{ for(int i=0;i<10;i++){ System.out.println("哒哒的马蹄"); } }).start(); } }
运行结果
lamdba表达式,对于一个方法可以推导出接口和类
lambda表达式快速入门
基本语法
(parameters)-> expression
(paramenters) -> { statements; }
实例:
简单表达式
()->“hello word”
无参数,返回一个字符串
(x)->”the content is:”+x;
接受一个参数,返回一个字符串
(x,y)->x+y
接受两个参数,返回一个值
(String x)->”this is the string:”+x;
接受一个字符串参数,返回一个字符串
上一篇:
通过多线程提高代码的执行效率例子