线程
1、三种创建方法
- 继承Thread
public class MyThread extends Thread {
public MyThread() {}
public MyThread(String name) {
super(name);
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(getName() + ":" + i);
}
}
}
public class TheadDemo {
public static void main(String[] args) {
MyThread t1 = new MyThread("线程1");
t1.start();
MyThread t2 = new MyThread("线程2");
// 守护线程,t1线程结束,t2随后也会结束,不一定能执行完成
t2.setDaemon(true);
t2.start();
}
}
- 实现 Runnable 接口
public class MyThread2 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
// 调用
MyThread2 t = new MyThread2();
Thread t1 = new Thread(t, "线程1");
Thread t2 = new Thread(t, "线程2");
t1.start();
t2.start();
- 实现 Callable 接口 和 Future 接口方式
// 1、实现 Callable 接口
Callable<Integer> callable =
new Callable<>() {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i < 101; i++) {
sum += i;
}
return sum;
}
};
// 2、创建任务
FutureTask<Integer> task = new FutureTask<>(callable);
// 3、把任务交给线程
Thread t1 = new Thread(task);
// 4、开启线程
t1.start();
// 5、获取返回值
Integer sum = task.get();
System.out.println(sum);