Java线程实现的三种模式

1)Thread:

public class ThreadTest extends Thread {

	public void run(){
		System.out.println(Thread.currentThread()+"say : hello");
	}
	
	public static void main(String[] args){
		new ThreadTest().start();
		new ThreadTest().start();
		new ThreadTest().start();
		new ThreadTest().start();
		new ThreadTest().start();
	}
}

执行结果:

Thread[Thread-2,5,main]say : hello
Thread[Thread-4,5,main]say : hello
Thread[Thread-3,5,main]say : hello
Thread[Thread-0,5,main]say : hello
Thread[Thread-1,5,main]say : hello

2)Runnable:

public class RunnableTest implements Runnable{

	public void run() {
		System.out.println(Thread.currentThread()+"say: hello");
	}
	
	public static void main(String[] args){
		RunnableTest rt = new RunnableTest();
		new Thread(rt,"111").start();
		new Thread(rt,"222").start();
		new Thread(rt,"333").start();
		new Thread(rt).start();
		new Thread(rt).start();
	}
}

执行结果:

Thread[111,5,main]say: hello
Thread[333,5,main]say: hello
Thread[Thread-0,5,main]say: hello
Thread[222,5,main]say: hello
Thread[Thread-1,5,main]say: hello


3)Callable:

public class CallableTest implements Callable<String>{//Callable<V>是泛型,不一定为String类型

	public String call() throws Exception {
		
		System.out.println(Thread.currentThread()+" say : hello");
		return "返回字符串:"+Thread.currentThread().toString();
		
	}
	public static void main(String[] args){
		//Callable和Future一个产生结果,一个拿到结果。
        //Callable接口类似于Runnable,但是Runnable不会返回结果,
		//而Callable可以返回结果,这个返回值可以被Future拿到,
		//也就是说,Future可以拿到异步执行任务的返回值。
		CallableTest ct = new CallableTest();//相当于Callable执行call()内容
		CallableTest ct2 = new CallableTest();
		
		FutureTask<String> ft = new FutureTask<>(ct);//相当于Futrue计算Callable返回的结果
		FutureTask<String> ft2 = new FutureTask<>(ct2);
		
		new Thread(ft,"有返回值得线程").start();
		new Thread(ft2).start();
		
		try {
			//callable的返回值
			System.out.println(ft.get());
			System.out.println(ft2.get());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

执行结果:

Thread[Thread-0,5,main] say : hello
Thread[有返回值得线程,5,main] say : hello
返回字符串:Thread[有返回值得线程,5,main]
返回字符串:Thread[Thread-0,5,main]

转载于:https://my.oschina.net/u/2329948/blog/784893

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值