class MyThread extends Thread {
@Override
public void run() {
System.out.println("继承Thread,重写run方法创建线程");
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("实现Runnable接口,重写run方法");
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread() {
@Override
public void run() {
System.out.println("使用匿名内部类创建 Thread 子类对象");
}
};
thread.start();
}
}
4.使用匿名内部类,实现Runnable接口
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("使用匿名内部类,实例Runnable接口作为构造参数");
}
});
thread.start();
}
}
5.lambda表达式
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("使用lambda表示创建线程");
});
thread.start();
}
}
6.实现Callable接口
class MyCallableTest implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("创建线程:" + Thread.currentThread().getName());
return 2;
}
}
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Integer> task = new FutureTask<>(new MyCallableTest());
Thread thread = new Thread(task);
thread.start();
System.out.println("创建线程的返回结果为:" + task.get());
}
}
7.使用线程池创建线程
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Pool {
public static void main(String[] args) {
ExecutorService pool = Executors.newCachedThreadPool();
pool.submit(new Runnable() {
@Override
public void run() {
//执行业务逻辑
for(int i = 1; i <= 100; i++) {
System.out.println("线程:" + Thread.currentThread().getName() + "执行了任务" + i + "~");
}
}
});
pool.submit(new Runnable() {
@Override
public void run() {
//执行业务逻辑
for(int i = 101; i <= 200; i++) {
System.out.println("线程:" + Thread.currentThread().getName() + "执行了任务" + i + "~");
}
}
});
pool.submit(new Runnable() {
@Override
public void run() {
//执行业务逻辑
for(int i = 201; i <= 300; i++) {
System.out.println("线程:" + Thread.currentThread().getName() + "执行了任务" + i + "~");
}
}
});
}
}