当前位置:   article > 正文

三种多线程使用框架_多线程框架

多线程框架

java三种多线程使用框架

1 Thread类使用框架

public class MyThread extends Thread{
	public void run() {}
}
public static void main(String[] args) {
		Thread threadA = new MyThread();
		Thread threadB = new MyThread();
		threadA.start();
		threadB.start();
        //或new Thread(new MyThread()).start();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2 Runnable类使用框架(解决Thread类无法多继承问题)

public class MyThread implements Runnable{
		public void run() {	}	
}
public static void main(String[] args) {
		MyThread mt = new MyThread();
		new Thread(mt).start();
		new Thread(mt).start();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

一层包裹,先实例化MyThread再用Thread包裹
Thread.start()启动多线程

3 Callable类使用框架(解决Thread无返回值问题)

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

class MyThread implements Callable<String>{
	public String call() {	}  //有返回值
}
	
public static void main(String[] args) throws InterruptedException, ExecutionException {
		MyThread mt = new MyThread();
		FutureTask<String> taskA = new FutureTask<String>(mt);
		FutureTask<String> taskB = new FutureTask<String>(mt);
				
		new Thread(taskA,  "线程A").start();
		new Thread(taskB,  "线程B").start();
	
		System.out.println(taskA.get()); //获取返回值
		System.out.println(taskB.get());
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

两层包裹,先实例化MyThread用FutureTask<泛型>类包裹,再用Thread包裹
Thread.start()启动多线程

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/177964?site
推荐阅读
相关标签
  

闽ICP备14008679号