目录
1、继承Thread类,重写run方法
class ThreadDemo extends Thread {
@Override
public void run() {
//多线程需要执行的代码
}
}
public class Test {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
// 1.创建线程
ThreadDemo threadDemo = new ThreadDemo();
// 2.启动线程
threadDemo.start();
}
}
}
2、实现Runnable接口,重写run方法
class RunnableDemo implements Runnable {
@Override
public void run() {
//多线程需要执行的代码
}
}
public class Test {
public static void main(String[] args) {
// 1.创建runable实现类
RunnableDemo runnableDemo = new RunnableDemo();
for (int i = 0; i < 10; i++) {
// 2.创建线程
Thread threadDemo = new Thread(runnableDemo);
// 3.启动线程
threadDemo.start();
}
}
}
3、使用匿名内部类方式
public class Test {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
public void run() {
多线程需要执行的代码
}
});
t1.start();
}
}
4、实现Callable接口,重写run方法
class CallableDemo implements Callable<String> {
@Override
public String call() throws Exception {
//多线程需要执行的代码
return "succeed";
}
}
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 1.创建callable实现类
CallableDemo callableDemo = new CallableDemo();
//创建一个FutureTask实现类
FutureTask<String> futureTask = new FutureTask<String>(callableDemo);
for (int i = 0; i < 10; i++) {
// 2.创建线程
Thread threadDemo = new Thread(futureTask);
// 3.启动线程
threadDemo.start();
//获得返回值
System.out.println(futureTask.get());
}
}
}
5、线程池
详见线程池篇