Java多线程的四种实现方式

Java多线程实现方式主要有四种:继承Thread类、实现Runnable接口、实现Callable接口通过FutureTask包装器来创建Thread线程、使用ExecutorService、Callable、Future实现有返回结果的多线程。

其中前两种方式线程执行完后都没有返回值,后两种是带返回值的。

1继承Thread类

Thread类本质上是实现了Runnable接口的一个实例,代表一个线程的实例。启动线程的唯一方法就是通过Thread类的start()实例方法。start()方法是一个native方法,它将启动一个新线程,并执行run()方法。这种方式实现多线程很简单,通过自己的类直接extend Thread,并复写run()方法,就可以启动新线程并执行自己定义的run()方法。例如:

public class ThreadDemo extends Thread{

	private String ThreadName;
	public ThreadDemo(String ThreadName){
		this.ThreadName = ThreadName;
	}
	public void run(){
		System.out.println("running--"+this.ThreadName+"---"+Thread.currentThread().getId());
	}
	
	public static void main(String[] args) {
		ThreadDemo threadDemo = new ThreadDemo("ThreadDemo_one");
		threadDemo.start();
		ThreadDemo threadDemo1 = new ThreadDemo("ThreadDemo_two");
		threadDemo1.start();
	}
}

2实现Runnable接口
如果自己的类已经extends另一个类,就无法直接extends Thread,此时,可以实现一个Runnable接口,如下:
 class RunnableDemo implements Runnable{
	private Thread t;
	private String threadName;
	RunnableDemo(String threadName){
		this.threadName = threadName;
		System.out.println("创建---"+threadName);
	}
	public void run(){
		System.out.println("running---"+threadName);
		try {
			for (int i = 0; i < 4; i++) {
				  System.out.println("Thread: " + threadName + ", " + i);
					Thread.sleep(5000);
			}
		} catch (InterruptedException e) {
			 System.out.println("Thread " +  threadName + " interrupted.");
		}
		 System.out.println("Thread " +  threadName + " exiting.");
	}
	public void start(){
		System.out.println("starting---"+threadName);
		if(t==null){
			t = new Thread(this,threadName);
			t.start();
		}
		
	}
	public static void main(String[] args) {
		RunnableDemo runnableDemo = new RunnableDemo("wq");
		runnableDemo.start();
		RunnableDemo runnableDemo1 = new RunnableDemo("css");
		runnableDemo1.start();
	}
}
3实现Callable接口通过FutureTask包装器来创建Thread线程
Callable接口(也只有一个方法)
FutureTask<Integer>是一个包装器,它通过接受Callable<Integer>来创建,它同时实现了Future和Runnable接口。
public class CallableDemo implements Callable<Integer>{

	public Integer call() throws Exception {
		 
		int i = 0;  
        for(;i<100;i++)  
        {  
            System.out.println(Thread.currentThread().getName()+" "+i);  
            
        }  
        return i;  
	}
	public static void main(String[] args) {
		CallableDemo call = new CallableDemo();
		FutureTask<Integer> ft = new FutureTask<Integer>(call);
//		new Thread(ft,"有返回值的线程").start();
		  for(int i = 0;i < 100;i++)  
	        {  
	            System.out.println(Thread.currentThread().getName()+" 的循环变量i的值"+i);  
	            if(i==21)  
	            {  
	                new Thread(ft,"有返回值的线程").start();  
	            }  
	        }  
		 try {
			System.out.println("子线程的返回值:"+ft.get());
		} catch (InterruptedException e) {
			
		} catch (ExecutionException e) {
			
		}  
	}
}
4ExecutorService、Callable、Future实现有返回结果的多线程
public class test {

	public static void main(String[] args) {
		ExecutorService threadPool = Executors.newFixedThreadPool(5);
		// newCachedThreadPool 创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
		// newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
		// newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
		// newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
		List<Future> futureList= new ArrayList<Future>();
		for (int i = 0; i <5; i++) {
			Callable task = new TestCallable("wq"+i, "phone"+i);
			Future<Object> f = threadPool.submit(task);
			futureList.add(f);
		}
		threadPool.shutdown();
		for (Future future : futureList) {
			try {
				System.out.println(future.get().toString());
			} catch (Exception e) {
				
				e.printStackTrace();
			} 
		}
		
	}
	
}
class TestCallable implements Callable<Object>{
	private String name;
	private String phone;
	 TestCallable(String name,String phone){
		this.name=name;
		this.phone=phone;
	}
	public Object call() throws Exception {
		 System.out.println(name+"----"+phone);
		return name+"--return--"+phone;
	}
	
}


猜你喜欢

转载自blog.csdn.net/wq_wangqiang/article/details/79194307