1.实现Runnable接口,重载run()
- public class ThreadRunnable implements Runnable {
- public void run() {
- for (int i = 0; i < 10; i++) {
- System.out.println(Thread.currentThread() + ":" + i);
- }
- }
- }
-
- public class ThreadMain {
- public static void main(String[] args)
- {
- ThreadRunnable threadRunnable = new ThreadRunnable();
- threadRunnable.run();
- }
- }
2.继承Thread类,复写run()
使用时通过调用Thread的start()(该方法是native),再执行创建线程的run()
不足:由于java为单继承,若使用线程类已经有个父类,则不能使用该方式创建线程。
- public class ThreadEx extends Thread {
- public void run() {
- for (int i = 0; i < 10; i++) {
- System.out.println(Thread.currentThread() + ":" + i);
- }
- }
- }
-
-
- public class ThreadMain {
- public static void main(String[] args)
- {
- ThreadEx threadEx = new ThreadEx();
- threadEx.start();
- }
- }
3.实现Callable接口,有返回值
补充:与实现Runnable接口类似,都是实现接口,不同的是该方式有返回值。
- import java.util.concurrent.Callable;
-
- public class ThreadCallable implements Callable {
- public Object call() throws Exception {
- for (int i = 0; i < 10; i++) {
- System.out.println(Thread.currentThread() + ":" + i);
- }
- return "succeed";
- }
- }
-
-
- public class ThreadMain {
- public static void main(String[] args) throws Exception
- {
- ThreadCallable threadCallable = new ThreadCallable();
- System.out.println(threadCallable.call());
- }
- }
4.使用Executors创建ExecutorService,入参Callable或Future
补充:适用于并发
未完待续,补充源码