1. 创建多线程方式一:
创建一个类继承Thread类 重写run 方法
class MyThread extends Thread{
public void run(){
}
}
创建类对象,
MyThread my=new MyThread();
my.start();
创建多线程方式二
创建一个类实现Runable接口 并重写run方法
class MyRunable implement Runable{
public void run(){
}
}
创建对象
MyRunable my=new MyRunable()
Thread thread=new Thread(my);//thread 称为代理对象
thread.start();
推荐使用第二种方式
第三种方法
Callable接口 重写call方法
class Call implements Callable{
public T call(){
}
}
创建对象
Call call1=new Call();
Call call2=new Call();
Call call3=new Call();
//创建线程池
Executors se=Executors.newFixedThreadPool(3);
//提交执行
Future result1=se.submit(call1);
Future result2=se.submit(call2);
Future result3=se.submit(call3);
//获取结果
T t=result1.get();
T t=result1.get();
T t=result1.get();
//关闭服务
t.shutdownNow();