JAVA创建多线程的三种方法

1.继承Thread

1.多线程方法

public class MyThread extends Thread{
	@Override
	public void run() {
		for (int i = 1; i <11 ; i++) {
			System.out.println(Thread.currentThread().getName()+"..."+System.currentTimeMillis());
		}	
	}

2.启动线程

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

2.实现Runable

1.多线程方法

public class MyRunable implements Runnable {
	@Override
	public void run() {
		for (int i = 1; i <11 ; i++) {
			System.out.println(Thread.currentThread().getName()+"..."+System.currentTimeMillis());
		}	
	}
}

2.启动线程

public static void main(String[] args) {
		Thread thread2=new Thread(new MyRunable());
		thread2.start()
	}

3.实现Callable

1.多线程方法

//实现Callable需要加上泛型
public class MyCallable implements Callable<String> {
	//重写call()方法,call方法有返回值,需和Callable中的泛型一致
	@Override
	public String call() throws Exception {
		for (int i = 1; i <11 ; i++) {
			System.out.println(Thread.currentThread().getName()+"..."+System.currentTimeMillis());
		}
		return "MyCallable执行完毕";
	}
}

2.启动线程

public static void main(String[] args) {
		FutureTask<String> task= new FutureTask<String>(new MyCallable());
		Thread thread3=new Thread(task);
		thread3.start()
	}

4.实现Runable和实现Callable的比较

  1. 实现Callable可以有返回值,实现Runable为返回值
  2. Callable的call()方法允许抛出异常,Runable的run()方法不能抛出异常
  3. 实现Callable可以监控线程状态,若无监控线程需求,可实现Runable
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值