Java 多线程以及区别

本文对比了Java中实现多线程的几种方式,包括通过Runnable接口、Callable接口及Thread类的区别。重点介绍了使用Runnable接口实现多线程的优势,并展示了如何利用Callable接口创建有返回值的线程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Runnable和<span style="color: rgb(51, 51, 51); font-family: Helvetica, Tahoma, Arial, sans-serif; font-size: 14px; line-height: 24px; background-color: rgb(245, 245, 245);">Thread区别</span>

如果一个类通过继承Thread来实现多线程的话,则不适合多个线程共享资源,而通过实现Runnable就可以做到这一点。

class MyTheard extends Thread{
	private int num = 5;//不能声明为静态的全局变量
	public void run(){
		for(int i=0;i<100;i++){
			if(num>0){
				System.out.println(Thread.currentThread().getName()+"卖票"+":"+(num--));
			}
		}
	}
}

public class TheardDemo01 {
	public static void main(String[] args) {
		MyTheard th1 = new MyTheard();
		MyTheard th2 = new MyTheard();
		MyTheard th3 = new MyTheard();
		th1.start();
		th2.start();
		th3.start();
	}

}
输出结果:
Thread-0卖票:5
Thread-0卖票:4
Thread-0卖票:3
Thread-0卖票:2
Thread-0卖票:1
Thread-2卖票:5
Thread-2卖票:4
Thread-2卖票:3
Thread-2卖票:2
Thread-2卖票:1
Thread-1卖票:5
Thread-1卖票:4
Thread-1卖票:3
Thread-1卖票:2
Thread-1卖票:1

class MyThread implements Runnable
{
	private int num = 5;
	public void run(){
		for(int i = 0;i<100;i++){
			if(num>0){
				System.out.println(Thread.currentThread().getName()+"卖票:"+" "+(num--));
			}
		}
	}
};

public class ThreadDemo02 
{
	public static void main(String[] args) 
	{
		MyThread mt = new MyThread();
		new Thread(mt).start();
		new Thread(mt).start();
		new Thread(mt).start();
	}
}

输出结果:
Thread-1卖票: 5
Thread-1卖票: 2
Thread-1卖票: 1
Thread-0卖票: 4
Thread-2卖票: 3
总结:
通过Rannable接口实现接口有如下的好处:
(1)适合于多个相同的程序代码的线程去处理同一资源。
(2)可以避免由于单继承带来的局限。
(3)增强了程序的健壮性,代码能够被多个线程共享,代码和数据独立。


  (3)实现Callable接口,重写call函数

        Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其它线程执行的任务。 

        Callable和Runnable有几点不同:

        ①Callable规定的方法是call(),而Runnable规定的方法是run(). 
        ②Callable的任务执行后可返回值,而Runnable的任务是不能返回值的
        ③call()方法可抛出异常,而run()方法是不能抛出异常的。 
        ④运行Callable任务可拿到一个Future对象,Future表示异步计算的结果。它提供了检查计算是否完成的方法,以等

        待计算的完成,并检索计算的结果.通过Future对象可了解任务执行情况,可取消任务的执行,还可获取任务执行的结果。


Java  Callable 代码示例:

class TaskWithResult implements Callable<String> {
	private int id;

	public TaskWithResult(int id) {
		this.id = id;
	}

	@Override
	public String call() throws Exception {
		return "result of TaskWithResult " + id;
	}
}

public class CallableTest {
	public static void main(String[] args) throws InterruptedException,
			ExecutionException {
		ExecutorService exec = Executors.newCachedThreadPool();
		ArrayList<Future<String>> results = new ArrayList<Future<String>>();	//Future 相当于是用来存放Executor执行的结果的一种容器
		for (int i = 0; i < 10; i++) {
			results.add(exec.submit(new TaskWithResult(i)));
		}
		for (Future<String> fs : results) {
			if (fs.isDone()) {
				System.out.println(fs.get());
			} else {
				System.out.println("Future result is not yet complete");
			}
		}
		exec.shutdown();
	}
}
运行结果:

    result of TaskWithResult 0
result of TaskWithResult 1
result of TaskWithResult 2
result of TaskWithResult 3
result of TaskWithResult 4
result of TaskWithResult 5
result of TaskWithResult 6
result of TaskWithResult 7
result of TaskWithResult 8
result of TaskWithResult 9





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值