代码 public class LamdaDemo{ public static void main( String[] args ) { Runnable task = () - { String threadName = Thread.currentThread().getName(); System.out.println("Hello " + threadName); }; task.run(); Thread thread = new Thread(task
代码
public class LamdaDemo
{
public static void main( String[] args )
{
Runnable task = () -> {
String threadName = Thread.currentThread().getName();
System.out.println("Hello " + threadName);
};
task.run();
Thread thread = new Thread(task);
thread.start();
System.out.println("Done!");
}
}
运行
Hello main Done! Hello Thread-0
补充知识:java_Thread多线程创建和lambda
我就废话不多说了,大家还是直接看代码吧~
/**
*
* @author Mr_zhou
* 2018年9月3日 下午6:42:38 <br/>
* TODO java多线程
*/
//----------------方式一实现Runnable接口----------------
public class TestThread implements Runnable
{
public static void main(String[] args)
{
ThreadPring();
}
static void ThreadPring()
{
//-------------------------方式二,new一个Runnable()匿名内部类----------------
Runnable run2=new Runnable()
{
@Override
public void run()
{
System.out.println(Thread.currentThread().getName());
}
};
//------------------------方式三,lambda简写,jdk1.8特性----------------
Runnable run=()->
{
System.out.println(Thread.currentThread().getName());
};
new Thread(run).start();
new Thread(run2).start();
new Thread(new TestThread()).start();
new myThread().start();
}
@Override
public void run()
{
try
{
//线程休眠3秒
Thread.sleep(3000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
//--------------方式四,继承线程类Thread----------------
class myThread extends Thread
{
@Override
public void run()
{
System.out.println(Thread.currentThread().getName());
}
}
以上这篇利用Lambda表达式创建新线程案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持易盾网络。
