1.继承Thread类进行实现
//继承Thread类进行实现
public class threadcase1 {
//定义一个类继承Thread
public static class MyThread extends Thread{
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(getName() + "HelloWorld");
}
}
}
public static void main(String[] args){
MyThread m1=new MyThread();
MyThread m2=new MyThread();
//给线程设置名字
m1.setName("进程1");
m2.setName("进程2");
//启动线程
m1.start();
m2.start();
}
}
2.利用Runnable接口实现
//利用Runnable接口实现
public class threadcase2 {
public static class run implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
//获取到当前线程的对象
Thread t=Thread.currentThread();
System.out.println(t.getName()+"HelloWorld");
}
}
}
public static void main(String[] args){
run r=new run();
//创建线程对象
Thread t1=new Thread(r);
Thread t2=new Thread(r);
//给线程设置名字
t1.setName("线程1");
t2.setName("线程2");
//启动线程
t1.start();
t2.start();
}
}
可以从结果看到并不是执行完线程一之后再执行线程二
想要获取多线程运行的结果, 可以用第三种方法
3.利用Callable接口和Future接口实现
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
//利用Callable接口和Future接口实现
public class threadcase3 {
public static class MyCallable implements Callable<Integer>{
@Override
public Integer call() throws Exception {
int sum=0;
for(int i=1;i<=100;i++){
sum+=i;
}
return sum;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建MyCallable对象(表示多线程要执行的任务)
MyCallable mc=new MyCallable();
//创建FutureTask对象(管理多线程运行的结果)
FutureTask<Integer>ft=new FutureTask<>(mc);
//创建线程的对象
Thread t=new Thread(ft);
//启动线程
t.start();
//输出结果为1到100的和,即 5050
System.out.println(ft.get());
}
}
初学者,见解不足,如有错误请指出