1.继承Thread类,重写run方法
class MyThread extends Thread{
@Override
public void run() {
System.out.println("这是一个线程");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new MyThread();
thread.start();
System.out.println("Hello world!");
}
}
注意这里用的是thread.start();不是thread.run();的原因是thread.start();是先去创建一个线程再来调用run方法,所以直接使用run方法是不会创建出一个线程的。
2.实现Runnable接口,重写run方法
class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("这是一个线程");
}
}
public class Demo {
public static void main(String[] args) {
Runnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
System.out.println("hello");
}
}
这里和第一种的区别就是解耦合,Runnable不在乎谁来创建线程,它只需要描述任务是什么就行,创建线程交给其他来实现。
3.继承Thread,但是使用匿名内部类
public class Demo2 {
public static void main(String[] args) {
Thread thread = new Thread() {
@Override
public void run() {
while (true) {
System.out.println("这是一个线程");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
};
thread.start();
while (true) {
System.out.println("hello");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
4.实现Runnable接口,但是使用匿名内部类
public class Demo3 {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("这是一个进程");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
};
Thread thread = new Thread(runnable);
thread.start();
System.out.println("hello");
}
}
5.利用lambda表达式(推荐)
public class Demo5 {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("这是一个线程");
});
thread.start();
System.out.println("hello");
}
}
这里lambad表达式是一个匿名函数(没有名字的函数,用一次就完了),主要用来实现回调函数(不是你主动调用的,也不是现在立即调用,通常是别人来调用)的效果。
6.实现Callable接口,重写call方法
适用于想让程序执行某个逻辑并且返回结果。
public class Test14 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i <= 1000; i++) {
sum +=i;
}
return sum;
}
};
FutureTask<Integer> task = new FutureTask<>(callable);
Thread t = new Thread(task);
t.start();
// 因为是并发执行,所以这里可能主线程执行完了,t线程没有执行完,但是这里的get会在t线程没有执行完之前会阻塞
System.out.println(task.get());
}
}
这里要注意的是Callable不能直接交给Thread去执行,需要用到FutureTask这个类包装一下。就相当于,你去吃麻辣香锅的时候选完菜之后会给你一个号码牌,待会会用号码牌去取菜。那这里的FutureTask就相当于这个号码牌的作用。
2万+

被折叠的 条评论
为什么被折叠?



