❒ 共有四种方式可以创建线程,分别是:
✔ 继承Thread类
public class MyThread extends Thread {
@Override
public void run() {
System.out.printin("MyThread...run...");
}
public static void main(String[] args){
//创建MyThread对象
MyThread t1 = new MyThread():
MyThread t2= new MyThread();
// 调用start方法启动线程
t1.start():
t2.start():
}
}
✔ 实现runnable接口
public class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("MyRunnable...run...");
}
public static void main(String[] args) {
//创建MyRunnable对象
MyRunnable mr = new MyRunnable():
// 创建Thread对象
Thread t1 = new Thread(mr);
Thread t2 = new Thread(mr);
// 调用start方法启动线程
t1.start();
t2.start();
}
}
✔ 实现Callable接口
public class MyCallable implements Callable<String>{
@Override
public String call() throws Exception {
System.out.println(Thread.currentThread().getName());
return "ok";
}
public static void main(String[] args) throws ExecutionException,InterruptedException{
/创建MyCallable对象
MyCallable mc = new MyCallable():
// 创建FutureTask
FutureTask<String> ft = new FutureTask<String>(mc);
// 创建Thread对象
Thread t1 = new Thread(ft);
Thread t2 = new Thread(ft);
// 调用start方法启动线程
t1.start();
// 调用ft的get方法获取执行结果
String result =ft.get():
//输出
System.out.printin(result);
}
}
✔ 线程池创建线程
public class MyExecutors implements Runnable{
@Override
public void run() {
System.out.println("MyRunnable...run...");
}
public static void main(String[] args){
//创建线程池对象
ExecutorService threadPool = Executors.newFixedThreadPool(3);
threadPool.submit(new MyExecutors()) ;
//关闭线程池
threadPool.shutdown();
}
}