目录
1、继承thread类
2、实现Runable接口
3、实现Callable和Future接口(优点是可以获取多线程的结果)
1、继承thread类
package com.jyt.thread;
/*
多线程启动的第一种方式:
1、自己定义一个类继承Thread
2、重写run方法
3、创建子类对象开启线程
*/
public class MyThread extends Thread{
@Override
//重写run方法,求1-100的和
public void run() {
int sum=0;
for (int i = 0; i <= 100; i++) {
sum+=i;
}
System.out.println(sum);
}
public static void main(String[] args) {
//实例化两个类对象,起名,开启线程
MyThread mt1=new MyThread();
MyThread mt2=new MyThread();
mt1.setName("线程1");
mt2.setName("线程2");
mt1.start();
mt2.start();
}
}
运行结果:
2、实现Runable接口
package com.jyt.thread;
/*
多线程的第二种实现方式:
1、自己定义一个类实现runable接口,
2、重写run方法
3、创建自己的类对象
4、创建thread对象,开启线程
*/
public class runable implements Runnable{
@Override
public void run() {
//线程1、2交替进行,分别输出10次hello
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+"hello"+i);
}
}
public static void main(String[] args) {
runable rb=new runable();//实例化runable的对象,相当于任务类
Thread th1=new Thread(rb);//将runable对象作为Thread的参数
Thread th2=new Thread(rb);
th1.setName("线程1");
th2.setName("线程2");
th1.start();
th2.start();
}
}
结果:
3、实现Callable和Future接口(优点是可以获取多线程的结果)
package com.jyt.thread;
/*
多线程的第三种实现方式:
1、创建类实现Callable接口,并重写call方法
2、实例化创建的类对象,即任务类
3、创建FutureTask对象,用于管理结果
4、创建thread对象,并start
*/
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class caller implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum=0;
for (int i = 0; i <= 10; i++) {
sum+=i;
}
return sum;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
caller ca= new caller();
FutureTask<Integer> ft=new FutureTask<>(ca);
Thread th=new Thread(ft);
th.start();
//显示结果
System.out.println(ft.get());
}
}
运行结果: