一、继承Thread
java
/**
* @Author : 一叶浮萍归大海
* @Date: 2023/11/20 9:39
* @Description: 创建线程的第一种方式:继承Thread
*/
public class CreateThreadDemo1 extends Thread {
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println(Thread.currentThread().getName() + i);
}
}
public static void main(String[] args) {
System.out.println("CreateThreadDemo1 main =================>");
CreateThreadDemo1 t1 = new CreateThreadDemo1();
CreateThreadDemo1 t2 = new CreateThreadDemo1();
CreateThreadDemo1 t3 = new CreateThreadDemo1();
t1.setName("aa");
t2.setName("bbbbbb");
t3.setName("ccccccccccccccccc");
t1.start();
t2.start();
t3.start();
}
}
二、实现Runnable
java
/**
* @Author : 一叶浮萍归大海
* @Date: 2023/11/20 9:39
* @Description: 创建线程的第二种方式:实现Runnable
*/
public class CreateThreadDemo2 implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println(Thread.currentThread().getName() + i);
}
}
public static void main(String[] args) {
System.out.println("CreateThreadDemo2 main =================>");
// CreateThreadDemo2 thread = new CreateThreadDemo2();
// Thread t1 = new Thread(thread, "aa");
// Thread t2 = new Thread(thread, "bbbbbb");
// Thread t3 = new Thread(thread, "ccccccccccccccccc");
//
// t1.start();
// t2.start();
// t3.start();
new Thread(() -> {
for (int i = 1; i <= 100; i++) {
System.out.println(Thread.currentThread().getName() + i);
}
}, "aa").start();
new Thread(() -> {
for (int i = 1; i <= 100; i++) {
System.out.println(Thread.currentThread().getName() + i);
}
}, "bbbbbb").start();
new Thread(() -> {
for (int i = 1; i <= 100; i++) {
System.out.println(Thread.currentThread().getName() + i);
}
}, "ccccccccccccccccc").start();
}
}
三、实现Callable
java
/**
* @Author : 一叶浮萍归大海
* @Date: 2023/11/20 9:39
* @Description: 创建线程的第二种方式:实现Callable
*/
public class CreateThreadDemo3 implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
return sum;
}
public static void main(String[] args) {
CreateThreadDemo3 thread = new CreateThreadDemo3();
FutureTask<Integer> futureTask = new FutureTask<>(thread);
new Thread(futureTask, "A").start();
new Thread(futureTask, "B").start();
new Thread(futureTask, "C").start();
try {
Integer result = futureTask.get();
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}