// 继承Thread
class MyThread extends Thread {
// 重写run方法执行任务
@Override
public void run() {
for (int i = 0; i < 10; i++) {
// 可以通过this拿到当前线程
System.out.println(this.getName()+"执行了"+i);
}
}
}
public class Demo_02_02_1_ThreadCreateWays {
public static void main(String[] args) {
// 先new出来,然后启动
MyThread myThread = new MyThread();
myThread.start();
for (int i = 0; i < 10; i++) {
// 通过Thread的静态方法拿到当前线程
System.out.println(Thread.currentThread().getName()+"执行了"+i);
}
}
}
// 实现Runnable接口
class MyThreadByRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
// 不能用this了
System.out.println(Thread.currentThread().getName() + "执行了" + i);
}
}
}
public class Demo_02_02_1_ThreadCreateWays {
public static void main(String[] args) {
// 实现Runnable接口的方式启动线程
Thread thread = new Thread(new MyThreadByRunnable());
thread.start();
for (int i = 0; i < 10; i++) {
// 通过Thread的静态方法拿到当前线程
System.out.println(Thread.currentThread().getName() + "执行了" + i);
}
}
}
new Thread(() -> {
System.out.println("Runnable是函数式接口, java8也可以使用lamba");
}).start();
// 使用Callable
class MyThreadByCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+"执行了"+i);
sum+=i;
}
return sum;
}
}
public class Demo_02_02_1_ThreadCreateWays {
public static void main(String[] args) {
// 用FutureTask包一层
FutureTask<Integer> futureTask = new FutureTask<>(new MyThreadByCallable());
new Thread(futureTask).start();
try {
// 调用futureTask的get能拿到返回的值
System.out.println(futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
MyThreadByRunnable myThreadByRunnable = new MyThreadByRunnable();
Thread thread = new Thread(myThreadByRunnable);
thread.start();
// 再来一个,复用了任务代码,继承Thread就不行
Thread thread2 = new Thread(myThreadByRunnable);
thread2.start();