目录
1.继承 Thread 类,重写 run
class MyThread extends Thread{
@Override
public void run() {
System.out.println("MyThread线程,启动!");
}
}
public class ThreadTest1 {
public static void main(String[] args) {
Thread t = new MyThread();
t.start();
}
}
此时点击运行 main 方法后,idea 对应的进程创建了一个 java 进程(为idea进程的子进程),这个 java 进程来执行我们刚刚写的代码。此时这各 java 进程里就有两个线程,一个是 main,一个是 t。
需要注意的是,我们的类继承 Thread 时,需要重写里面的 run() 方法,这个 run 方法的方法体就是我们要实现的功能,但是我们在创建线程后,启动线程使用的是 start() 方法,而不是 run()。
2. 实现 Runnable 接口,重写 run
class MyRunnable implements Runnable{
@Override
public void run() {
while (true) {
System.out.println("Runnable, 启动!");
}
}
}
public class ThreadTest2 {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread t = new Thread(runnable);
t.start();
}
}
3. 继承 Thread,使用匿名内部类
public class ThreadTest3 {
public static void main(String[] args) {
Thread t = new Thread(){
@Override
public void run() {
System.out.println("匿名内部类,启动!");
}
};
t.start();
}
}
4. 实现 Runnable,使用匿名内部类
public class ThreadTest4 {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("匿名内部类,启动!");
}
});
t.start();
}
}
5. 使用 lambda 表达式
public class ThreadTest5 {
public static void main(String[] args) {
Thread t = new Thread(() -> {
System.out.println("lambda表达式,启动!");
});
t.start();
}
}
这种 lambda 表达式的写法最为常见。
6. 实现 Callable 接口
这个 Callable 其实和 Runnable 差不多,只不过 Runnable 没有返回值,但是有时候我们确实需要返回值,于是就有了 Callable 的出现,我们用代码来看看 Callable 的使用吧:
public static void main(String[] args) throws ExecutionException, InterruptedException {
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i <= 1000; i++) {
sum += i;
}
return sum;
}
};
FutureTask<Integer> futureTask = new FutureTask<>(callable);
Thread t = new Thread(futureTask);
t.start();
System.out.println(futureTask.get());
}
运行代码:
此时我们可以发现 Callable 还有一个与 Runnable 不同的地方,就是 Callable 的匿名内部类对象不能直接放到 Thread参数中,必须包一层 FutureTask 类,这个类其实就是得到返回值的类,里面的 get 方法就鞥的得到返回值。