Java中多线程的四种实现方法

在java中多线程有以下四种方法:

 一、继承Thread类实现多线程

继承Thread类并且覆写run()方法来实现多线程,继承Thread类需要需要注意一个线程只能调用一次start()方法。

如以下代码:

             

class Mythread extends Thread{
	private String title;
	public Mythread(String title){
		this.title=title;
	}
	public void run(){
		for(int i=0;i<10;i++){
			System.out.println(this.title+",i= "+i);
		}
	}
}
public class Test {
	public static void main(String[] args) {
		Mythread thread1=new Mythread("线程1");
		Mythread thread2=new Mythread("线程2");
		Mythread thread3=new Mythread("线程3");
		thread1.start();
		thread2.start();
		thread3.start();
	}

}

 

由于Thread是一个类,因此会有多继承局限,因此引入了一个接口Runnable()接口来实现多线程

 

二、继承Runnable()接口来实现多线程

 继承Runnable()实现多线程由代码所示:

                                     

package Runnable;

class Mythread implements Runnable{

	private String title;
	public Mythread(String title){
		this.title=title;
	}
	
	public void run() {
		for(int i=0;i<10;i++){
			System.out.println(this.title+",i= "+i);
		}
	}
}

public class Test {

	public static void main(String[] args) {
		Mythread thread1=new Mythread("线程1");
		Mythread thread2=new Mythread("线程2");
		Mythread thread3=new Mythread("线程3");
		new Thread(thread1).start();
		new Thread(thread2).start();
		new Thread(thread3).start();
	}

}

   由于Runnable()接口中没有提供start()方法来启动多线程,因此我们在产生实例化对象时需要借助于Thread()提供的start()

方法来启动多线程。

使用Runnable和Thread来实现多线程有以下两种主要的区别:

1.Runnable实现多线程时,可以避免多线程局限。

2.使用Runnable实现多线程的程序类可以更好的描述出程序共享的概念。 当然并不是说Thread不能。

 

三、Callable实现多线程

 

import java.util.concurrent.FutureTask;



class Mythread implements Callable<String>{

	private int ticket=10;
	public String call() throws Exception {
		while(this.ticket>0){
			System.out.println("剩余票数:"+this.ticket--);
		}
		return "票卖完了";
	}
}
public class Test {
	public static void main(String[] args) throws InterruptedException, ExecutionException 
	{
		FutureTask<String> task=new FutureTask<String>(new Mythread());
		new Thread(task).start();
		new Thread(task,"线程1").start();
		System.out.println(task.get());
	}

}

我们可以观察到Callable也是一个接口,它与Runnable()差别主要是在:

  1.   Callable规定的方法是call(),而Runnable规定的方法是run(). 
  2.   Callable的任务执行后可返回值,而Runnable的任务是不能返回值的。  
  3.   call()方法可抛出异常,而run()方法是不能抛出异常的。 
  4.   运行Callable任务可拿到一个Future对象, Future表示异步计算的结果。 
  5.   通过Future对象可了解任务执行情况,可取消任务的执行,还可获取任务执行的结果。 

 

四、ExecutorService、Callable、Future实现有返回结果的多线程

  

public class test {
 
	public static void main(String[] args) {
		ExecutorService threadPool = Executors.newFixedThreadPool(5);
		// newCachedThreadPool 创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
		// newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
		// newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
		// newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
		List<Future> futureList= new ArrayList<Future>();
		for (int i = 0; i <5; i++) {
			Callable task = new TestCallable("wq"+i, "phone"+i);
			Future<Object> f = threadPool.submit(task);
			futureList.add(f);
		}
		threadPool.shutdown();
		for (Future future : futureList) {
			try {
				System.out.println(future.get().toString());
			} catch (Exception e) {
				
				e.printStackTrace();
			} 
		}
		
	}
	
}
class TestCallable implements Callable<Object>{
	private String name;
	private String phone;
	 TestCallable(String name,String phone){
		this.name=name;
		this.phone=phone;
	}
	public Object call() throws Exception {
		 System.out.println(name+"----"+phone);
		return name+"--return--"+phone;
	}
	
}

Java中多线程的方法有多种多样,每种方法也各有优劣,在不同的环境下,最好能灵活的选用不同的调用方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值