多线程
实现方法
- 1.继承Thread类的方式进行实现
- 2.实现Runnable接口的方式进行实现
- 3.利用Callable接口和Future接口方式实现
继承Thread类的方式进行实现
步骤
- 1.定义一个类继承Thread
- 2.重写run方法
- 3.创建子类对象,并启动线程(start方法
代码
public class MyThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("hello world!"+this.getName());
}
}
}
public class Main {
public static void main(String[] args) {
MyThread mt1 = new MyThread();
MyThread mt2 = new MyThread();
mt1.setName("t1");
mt2.setName("t2");
mt1.start();
mt2.start();
}
}
实现Runnable接口的方式进行实现
步骤
- 1.自己定义一个类实现Runnable接口
- 2.重写里面的run方法
- 3.创建自己的类的对象
- 4.创建一个Thread类的对象,并开启线程
代码
public class MyThread implements Runnable {
@Override
public void run() {
Thread t = Thread.currentThread();
for (int i = 0; i < 10; i++) {
System.out.println("hello world!"+t.getName());
}
}
}
public class Main {
public static void main(String[] args) {
MyThread mt1 = new MyThread();
MyThread mt2 = new MyThread();
Thread t1 = new Thread(mt1);
Thread t2 = new Thread(mt2);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
利用Callable接口和Future接口方式实现
步骤
- 1.创建一个类实现Callable接口
- 2.重写call(是有返回值的,表示多线程运行的结果)
- 3.创键实现Callable接口的对象(表示多线程要执行的任务
- 4.创建FutureTask对象(作用管理多线程运行的结果
- 5.创建Thread类的对象,并启动(表示线程
代码
public class MyThread implements Callable