Java线程实现/创建方式
继承Thread类
Thread类本质上是实现了Runnable接口的一个代表线程的实例。当我们使用继承thread类时,我们需要使用Thread的start()方法。start()方法会为我们开启一个新的线程和执行run()方法。
public class MyThread extends Thread{
public void run(){
System.out.println("Start a new Thread ... ");
}
}
MyThread myThread = new MyThread();
// start方法会为我们调用myThrea里的run方法
myThread.start();
实现Runnable接口
当一个类已经继承了其他类时,再想要通过继承Thread来实现多线程肯定是不现实的。那我们可以直接让这个类实现Runnable接口,然后再实例化一个Thread,并把我们这个类的实例传入Thread来,并由Thread实例调用run方法实现多线程。
public class MyThread extends otherclass implments Runnable{
public void run(){
System.out.println("Start a new Thread ... ");
}
}
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread);
thread.run();
ExecutorService,Callable,Future实现有返回值线程
前面两种继承Thread和实现Runnable接口都没法给予用户定义的返回值,那如果我们想要实现具有返回值的多线程,可以使用Callable接口,然后获取返回的Future对象,对这个对象调用get方法就可以得到返回的对象了。将Callable接口和线程池ExecutorService结合起来,就可以实现具有返回值的多线程了。
// 创建一个内有10个线程的线程池
ExecutorService threadPool = new ExecutorService(10);
// 存储所有callable返回的future对象
List<Future> list = new ArrayList<Future>();
for(int i = 0; i < 10; i++){
Callable c = new Callable(i);
Future future = pool.submit(c);
list.add(future);
}
pool.shutdown();
for(Future future:list){
System.out.println("Content is ... " + future.get().toString());
}
使用线程池
ExecutorService threadPool = new ExecutorService(10);
while(true){
threadPool.execute(new Runnable(){
@Override
public void run(){
System.out.println(Thread.currentThread().getName()+"is running...");
}
)
}