Java实现多线程的四种方法

参考文章:https://www.cnblogs.com/felixzh/p/6036074.html

java实现多线程的四种方法:

1,继承Thread类

2,实现Runnable接口

3,实现Callable接口通过FutureTask包装器来创建Thread线程

4,使用ExecutorService、Callable、Future实现有返回结果的多线程。

下面是举例:

1,继承Thread类

package com.thread;
/*
 * Thread类实现runnable接口,重写runnable接口来实现自定义的业务逻辑
 * thread.run()没有创建新的线程,只是执行run()里的内容
 * thread.start()调用native方法,也就是非java语言实现的方法,创建新线程并调用run方法
 */
public class MyThread extends Thread{

	public void run() {
		System.out.println("mythread.run()");
	}
	
	public static void main(String[] args) {
		MyThread thread1 = new MyThread();
		MyThread thread2 = new MyThread();
		thread1.start();
		thread2.start();
		
	}
}

2,实现Runnable接口

package com.runnable;

public class RunnableTest implements Runnable{

	@Override
	public void run() {
		System.out.println("mythread.run()");
		
	}
	
	public static void main(String[] args) {
		//先创建一个实现了runnable接口的类
		RunnableTest runnableTest = new RunnableTest();
		/*
		 * 然后将类放入Thread中
		 * 当传入runnable target参数给Thread后,thread的run方法会调用target.run()
		 */
		Thread thread = new Thread(runnableTest);
		thread.start();
	}

}

3,实现Callable接口通过FutureTask包装器来创建Thread线程

package com.futureTask;

import java.util.concurrent.Callable;

/*
 * 想要建立FutureTask,首先要创建一个实现Callable的类
 */
public class CallableFirst<V> implements Callable<V>{

	@Override
	public V call() throws Exception {
		return null;
	}

}
package com.futureTask;

import java.util.concurrent.FutureTask;
/*
 *  执行顺序:
 *  thread.start(),开启线程并执行runnable的run方法
 *  futureTask的run方法内部调用callable的call方法
  *        执行我们自己实现callable类的call方法
 */
public class FutureTaskTest {
	
	public static void main(String[] args) {
		CallableFirst callable = new CallableFirst();
		//将实现callable的类放入futureTask
		FutureTask oneTask = new FutureTask(callable);
		//将FutureTask放入Thread
		Thread oneThread = new Thread(oneTask);
		oneThread.start();
	}

}

4,使用ExecutorService、Callable、Future实现有返回结果的多线程。

package com.executor;

import java.util.concurrent.Callable;

public class MyCallable<Object> implements Callable<Object>{
	
	private String taskNum;
	
	public MyCallable(String taskNum) {
		this.taskNum = taskNum;
	}

	@Override
	public Object call() throws Exception {
	   return (Object)(taskNum+"执行了自定义的call方法");
	}

}
package com.executor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/*
 *  执行顺序:
 *  自定义实现callable接口的类
 *  将实现callable接口的类放入线程池,Executors.newFixedThreadPoll(int)返回ThreadPoolExcutor
 *  ThreadPoolExecutor实现了AbstractExcutorService,AbstractExcutorService实现了ExcutorService
 *  抽象类AbstractExecutorService实现了ExecutorService接口的submit(callable)方法:
 *  public <T> Future<T> submit(Callable<T> task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task);//讲callable变为runnable
        execute(ftask);
        return ftask;
    }
    execute:线程数相关判断,另外,调用addWorker,该方法调用new Worker(),实现runnable接口的类被放入task
    获取worker中的线程,并start(),也就是调用runWorker(task),该方法调用task.run()
 *  
 */
@SuppressWarnings("unchecked")  
public class ExecutorTest{  

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		System.out.println("----程序开始运行----");

		final int taskSize = 5;
		ExecutorService pool = Executors.newFixedThreadPool(taskSize);
		// 创建多个有返回值的任务
		List<Future> list = new ArrayList<Future>();
		for (int i = 0; i < taskSize; i++) {
			Callable c = new MyCallable(i + " ");
			// 执行任务并获取Future对象
			Future f = pool.submit(c);
			list.add(f);
		}
		// 关闭线程池
		pool.shutdown();

		// 获取所有并发任务的运行结果
		for (Future f : list) {
			// 调用get方法阻塞等待任务的执行结果返回
			System.out.println(">>>" + f.get().toString());
		}

		System.out.println("----程序结束运行----");
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值