通过继承Thread类来实现多线程
package com.z.test;
/**
*
* @author
*通过继承Thread类来实现多线程
*/
public class ThreadT {
public static void main(String[] args) {
//主线程打印 总是先运行主线程
//系统默认只运行主线程,只有当线程start是,才会运行子线程
new thread1().start();
System.out.println("主线程"+Thread.currentThread().getId());
}
}
class thread1 extends Thread {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("子线程"+Thread.currentThread().getId());
}
}
【结果】 主线程1
子线程10
实现Runnable接口实现多线程,必须重写run方法
package com.z.test;
public class RunnableT implements Runnable {
//实现Runnable接口实现多线程,必须重写run方法
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("子线程 "+Thread.currentThread().getId());
}
public static void main(String[] args) {
RunnableT t =new RunnableT();
new Thread(t).start();
System.out.println("主线程");
}
}
【结果】主线程
子线程 10
实现Callable接口,重写call方法,通过FutureTask类来实现多线程
package com.z.test;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class EF implements Callable<String>{
/**
* 实现Callable接口,重写call方法,通过FutureTask类来实现
*/
@Override
public String call() throws Exception {
// TODO Auto-generated method stub
String str=Thread.currentThread().getId()+"线程正在运行";
return str;
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
EF t=new EF();
FutureTask<String> task=new FutureTask<>(t);
new Thread(task).start();//只有启动没有打印内容
//获取call方法返回的内容
System.out.println(task.get()); //会抛出一个异常
System.out.println("主线程正在运行...");
}
}
【结果】 10线程正在运行
主线程正在运行...