目录
实现Runnable接口
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(new Runnable() {//这里采用了匿名函数的方式,可以写一个类实现接口Runnable,new MyRunnable(){}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + System.currentTimeMillis());
}
}).start();
}
}
继承Thread
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new MyThread().run();
}
}
static class MyThread extends Thread{//Thread实现了Runable接口
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + System.currentTimeMillis());
}
}
通过FuturerTask和Callable
public static void main(String[] args) throws ExecutionException, InterruptedException {
for (int i = 0; i < 100; i++) {
new Thread(new FutureTask<>(new Callable<Integer>() {//FutureTask实现了Runnable接口
@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName() + System.currentTimeMillis());
return 1;
}
})).start();
}
}
拓展:lambda表达式
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
Runnable是函数式接口:函数式接口都可以使用lambda表达式和函数式引用简化:
new Thread(ThreadTest::incre).start();//Runnable调用run=ThreadTest的incre
new Thread(() -> { System.out.println("hello world");//Runnable调用run=输出一句话helloWorld}).start();
可以这么理解:如果传入的是函数式接口对象参数,那么就只着眼于里面的唯一抽象方法怎么做就好