方式一:继承Thread类的方式进行实现
步骤:
1、自己定义一个类继承Thread
2、重写run方法
3、创建子类的对象,并启动线程
e.g.
public class MyThread extends Thread{
@Override
public void run(){
//书写线程要执行的代码
for(int i=0;i<100;i++){
System.out.println(getName()+"Hello");
}
}
}
在main方法里面创建子类对象,开启线程
{
MyThread t1 = new MyThread();
//这样可以看到线程交替执行的效果
//开启线程
t1.start();
}
方式二:实现Runnable接口的方式进行实现
步骤:
1、自己定义一个类实现Runnable接口
2、重写run方法
3、创建自己的类的对象(表示多线程要执行的任务)
4、创建一个Thread类的对象,并开启线程
e.g.
public class MyRun implements Runnable{
@Override
public void run(){
//书写线程要执行的代码
for(int i=0;i<100;i++){
//获取到当前线程的对象
Thread t = Thread.currentThread();
System.out.println(t.getName()+"Hello");
}
}
}
main{
MyRun mr = new MyRun();
Thread t1 = new thread(mr);
Thread t2 = new thread(mr);
t1.start();
}
方式三:利用Callable接口和Future接口方式实现
特点:可以获取到多线程运行的结果
步骤:
1、创建一个类MyCallable实现Callable接口
2、重写call(是有返回值的,表示多线程运行的结果)
3、创建MyCallable的对象(表示多线程要执行的任务)
4、创建FutureTask的对象(作用管理多线程运行的结果)
5、创建Thread类的对象,并启动(表示线程)
e.g.
public class MyCallable implements Callable<Integer>{
@Override
public Integer call() throws Exception{
//求1-100之间的和
int sum=0;
for(int i=1;i<=100;i++)
{
sum=sum+i;
}
return sum;
}
}
main{
MyCallable mc =new MyCallable();
FutureTask<Integer> ft = new FutureTask<>(mc);
Thread t1 new Thread(ft);
t1.start();
//获取多线程运行的结果
Integer result = ft.get();
System.out.println(result);
}