多线程的三重实现方式(java基础)
方式一
- 自己定义一个类继承Thread
- 重写run
- 创建子类对象,并启动线程
子类
package com.itheima.demo;
class MyThread extends Thread {
@Override
public void run() {
//重写线程要执行的代码
//现在的cpu计算能力太强,若是执行的循环次数太少可能看不到轮替执行,
for (int i = 0; i < 1000; i++) {
// getName() 可以拿到线程的名字,区分哪个线程在执行
System.out.println(getName() + "helloWorld");
}
}
}
主类
package com.itheima.demo;
public class Demo_thread {
public static void main(String[] args) {
/**
* 多线程的第一种启动方式
* 1.自己定义一个类继承Thread
* 2.重写run
* 3.创建子类对象,并启动线程
*/
//创建子类对象
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
//给线设置name以区分哪个线程在执行
t1.setName("张三");
t2.setName("李四");
//开启线程
t1.start();
t2.start();
}
}
效果
张三helloWorld
张三helloWorld
李四helloWorld
李四helloWorld
张三helloWorld
张三helloWorld
李四helloWorld
李四helloWorld
张三helloWorld
张三helloWorld
李四helloWorld
张三helloWorld
#可以看到交替执行
方式二
- 自定义一个类实现Runnable接口
- 重写run方法
- 创建自己类的对象
- 创建一个Thread类的对象,并开启线程
子类
package com.itheima.demo2;
public class MyRun implements Runnable {
@Override
public void run() {
//重写线程要执行的代码
//现在的cpu计算能力太强,若是执行的循环次数太少可能看不到轮替执行,
for (int i = 0; i < 1000; i++) {
//获取当前线程对象
Thread thread = Thread.currentThread();
System.out.println(thread.getName() + "helloWorld");
}
}
}
主类
package com.itheima.demo2;
public class MyThread {
public static void main(String[] args) {
/**
* 多线程的第二种启动方式
* 1.自定义一个类实现Runnable接口
* 2.重写run方法
* 3.创建自己类的对象
* 4.创建一个Thread类的对象,并开启线程
*/
MyRun mr = new MyRun();
Thread t1 = new Thread(mr);
Thread t2 = new Thread(mr);
//给线程设置name以区分哪个线程在执行
t1.setName("张三");
t2.setName("李四");
t1.start();
t2.start();
}
}
效果
李四helloWorld
李四helloWorld
张三helloWorld
李四helloWorld
张三helloWorld
张三helloWorld
李四helloWorld
李四helloWorld
张三helloWorld
张三helloWorld
李四helloWorld
李四helloWorld
方式三
子类
package com.itheima.demo3;
import java.util.concurrent.Callable;
public class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i <= 100; i++) {
sum += i;
}
return sum;
}
}
主类
package com.itheima.demo3;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class demo3 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
/**
*
* 特点:可以获取多线程运行的结果
*
* 1.创建一个类实现Callable接口
* 2.重写call(有返回值,表示多线程的执行结果)
* 3.创建自定义类的对象(表示多线程要执行的任务)
* 4.创建FutureTask对象(管理多线程运行的结果)
* 5.创建Thread对象,并启动
*/
//创建自定义类的对象(表示多线程要执行的任务)
MyCallable mc = new MyCallable();
//创建FutureTask对象(管理多线程运行的结果)
FutureTask<Integer> ft = new FutureTask<>(mc);
//5.创建Thread对象,并启动
Thread t1 = new Thread(ft);
t1.start();
Integer result = ft.get();
System.out.println(result);
}
}