
多线程实现的四种方式:
目录
一.继承Thread类
二.实现Runnable接口
三.实现Callable接口
四.创建线程池
1.自定义一个类,继承java.lang包下的Thread类
2.重写run方法,将要执行的代码块写在run方法中
3.在另一个类中创建子类对象
4.调用star方法启动线程
//继承Thread类
public class Test extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("hello world");
}
}
}
public class Test01{
public static void main(String[] args) {
//创建上面类的对象
Test t = new Test();
//调用star,启动线程
t.start();
}
}
1.和继承Tread的方式,推荐使用实现Runnable的方式
a.线程和任务分离,解耦合,提高代码的健壮性
b.避免了Java单继承的局限性
c.线程池中,只能传入Runnable和Callable类型的对象
d.每一个线程启动后都有一个栈,各自在各自的栈中执行任务。所有线程的开销比一般对象开销大
1.自定义一个类,实现java.lang包下的Runnable类
2.重写run方法,将要执行的代码块写在run方法中
3.在另一个类中创建子类对象
4.用实现Runnable接口的对象作为参数实例化一个Thread对象
5.调用Tread的star方法启动线程
//实现Runnable接口
public class Runnable01 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("world");
}
}
}
public class Test {
public static void main(String[] args) {
Runnable01 r = new Runnable01();
//创建Thread对象并将上面自定义类的对象作为参数传递给Thread的构造方法中。
Thread t = new Thread(r);
t.start();
for (int i = 0; i < 10; i++) {
System.out.println("hello");
}
}
}
1.自定义一个类,实现java.util.concurrent包下的Callable类
2.重写call方法,将要执行的代码块写在call方法中
3.创建实现Callable接口的自定义类对象
4.创建ExecutorSercice线程池,将自定义的对象放入线程池中
5.获取线程返回结果
6.关闭线程
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
public class Test {
public static void main(String ards[]) throws InterruptedException, ExecutionException{
for(int i=0;i<10;i++){
Callable c = new callableTest();
FutureTask f = new FutureTask(c);
new Thread(f).start();
System.out.println(Thread.currentThread().getName()+"----"+f.get());
}
System.out.println(Thread.currentThread().getName());
}
}
class callableTest implements Callable>{
@Override
public Integer call() throws Exception {
int result = 0;
for(int i=0;i<10;i++){
result += i;
}
System.out.println(Thread.currentThread().getName());
return result;
}
}
a.提高响应速度。预先创建好了线程,只等任务过来执行;
b.降低资源消耗。线程池中的线程执行完任务,又返回到线程池中,等待下一个任务来后可以继续使用该线程;
c.提高线程的可管理性。一个线程大约需要1M的空间,线程池可以设置最大线程数量
1. 创建一个类实现Callable接口
2. 重写 call() 方法
3. 创建线程池
4. 创建接收结果的列表集合
5. 创建线程对象
6. 将线程对象提交到线程池中,并将返回结果接收
7. 将返回结果加入结果集合
8. 关闭线程池
public class CThread implements Callable{ private String name; public Method(String name ) { this.name = name; } //重写call()方法 @Override public String call() throws Exception { return name; } } //调用线程 //创建线程池 ExecutorService pool = Executors.newFixedThreadPool(5); List list = new ArrayList (); for(int i = 0;i<5;i++) { //创建线程对象 Callable c = new CThread("线程"+i); //将线程对象提交到线程池中,并将返回结果接收 Future f= pool.submit(c); System.out.println("线程"+i); list.add(f); } //关闭线程池 pool.shutdown(); //打印返回结果 for (Future future : list) { try { System.out.println(future.get().toString()); } catch (InterruptedException | ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } }