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{//Callable是泛型,不一定为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 ft = new FutureTask<>(ct);//相当于Futrue计算Callable返回的结果
		FutureTask 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

你可能感兴趣的:(java)