Java线程实现的三种模式

1)Thread:java

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:code

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:get

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();
		}
	}
}

执行结果:io

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

相关文章
相关标签/搜索