java中实现多线程的三种方式
继承Thread类
public class ExtendsThreadWay extends Thread{
@Override
public void run() {//重写 run 方法
for (int i = 0; i < 10; i++) {
System.out.println("------多线程-------" + i);
}
}
public static void main(String[] args) {
ExtendsThreadWay et = new ExtendsThreadWay();
et.start();
for (int i = 0; i < 10; i++) {
System.out.println("主线程" + i);
}
}
}
实现Runable接口
public class AchieveRunnableWay implements Runnable{
@Override
public void run() {//实现接口
for (int i = 0; i < 10; i++) {
System.out.println("------多线程-------" + i);
}
}
public static void main(String[] args) {
Thread t = new Thread(new AchieveRunnableWay());
t.start();
for (int i = 0; i < 10; i++) {
System.out.println("主线程" + i);
}
}
}
实现callable接口和future对象
public class AchieveCallableWay implements Callable<String> {
@Override
public String call() throws Exception {
for (int i = 0; i < 10; i++) {
System.out.println("------多线程-------" + i);
}
return null;
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
//其实就三步:1 创建Callable实例
//2将Callable实例设置进FutureTask实例中
//3将FutureTask实例作为Runnable类型设置进Thread中
AchieveCallableWay task = new AchieveCallableWay();
FutureTask f = new FutureTask(task);
new Thread(f).start();
for (int i = 0; i < 10; i++) {
System.out.println("主线程" + i);
}
}
}