Java创建线程的方式

Java中创建线程有三种,分别为实现Runnable接口,继承Thread类,实现Callable接口。

1.Thread

public class MyThread extends Thread {

	public MyThread() {
		this.setName("MyThread");
	}

	public void run() {
		
		while(true){
			System.out.println("当前运行的线程: "+this.getName());
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
	
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String []args){
		
		new MyThread().start();
		
	}
}
  • 优点:在run方法内直接用this获取当前线程,无需使用Thread.currentThread()
  • 缺点:Java不支持多继承,如果继承Thread类,就不能继承其它类。任务与线程没有分离,对于多个线程执行一样的任务时需要多份任务代码,而Runnable没有这个限制。

2.Runnable接口

public class RunnableTask implements Runnable {

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (true) {
			System.out.println("当前运行的线程: " + Thread.currentThread().getName());

			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) throws InterruptedException {
		
		RunnableTask task = new RunnableTask();
		new Thread(task).start();
		new Thread(task).start();

		
	}

}

以上两种方式没有返回值。

3.Callable接口


public class CallableTest {
	public static void main(String []args) throws Exception {
		
		Callable<Integer> call  = new Callable<Integer>() {
			
			@Override
			public Integer call() throws Exception {
				System.out.println("thread start..");
				Thread.sleep(2000);
				return 1;
			}
		};
		
		FutureTask<Integer> task = new FutureTask<>(call);
		Thread t = new Thread(task);
		
		t.start();
		System.out.println("do other thing..");
		System.out.println("拿到线程的执行结果 : " + task.get());
	}
}

控制台输出:

do other thing..
thread start..
拿到线程的执行结果 : 1

Callable和Runnable的区别:

  • Callable定义的方法是call,而Runnable定义的方法是run。
  • Callable的call方法可以有返回值,而Runnable的run方法不能有返回值。
  • Callable的call方法可抛出异常,而Runnable的run方法不能抛出异常。 

转载于:https://my.oschina.net/u/4045381/blog/3079970

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值