线程,线程池基础
package thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 创建线程的三种方式:
* 1)实现 Runnable接口
* 2)继承Thread类
* 3)通过Callable和Future创建线程
* <p>
* 线程资源必须通过线程池提供:使用线程的好处:减少创建和销毁线程所花的时间以及系统资源的开销,解决资源不足的问题。
* 如果不适用线程池,有可能造成系统创建大量同类线程而导致消耗完内存或者”过度切换“的问题。
* <p>
* 使用线程池的目的:
* 1)线程是子缺资源,不能频繁的创建。
* 2)解耦:线程的创建与执行完全分开,方便维护。
* <p>
* 常见的创建线程池的方式有:
* 1)Executors.newCachedThreadPool():无限线程池
* 2)Executors.newFixedTreadPool(nThreads):创建固定大小线程池
* 3)Executors.newSingleThreadExecutors():创建单个线程的线程池
*/
// public class MyThread extends Thread {
// @Override
// public void run() {
// for (int i = 0; i <= 5; i++) {
// System.out.println(Thread.currentThread().getName() + "run" + i + "times");
// }
// }
// }
public class MyThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "run" + i + "times");
}
}
}
// public class MyThread implements Callable{
// @Override
// public Object call() throws Exception {
// Thread.sleep(3000);
// return 1;
// }
// }
class ThreadDemo {
public static void main(String[] args) {
// 继承Thread类
// MyThread thread1 = new MyThread();
// MyThread thread2 = new MyThread();
// thread1.start();
// thread2.start();
// 实现Runnable接口
// MyThread thread1 = new MyThread();
// MyThread thread2 = new MyThread();
// new Thread(thread1).start();
// new Thread(thread2).start();
// 实现Callable接口
// FutureTask futureTask = new FutureTask(new MyThread());
// new Thread(futureTask).start();
//
// try {
// Object result = futureTask.get();
// System.out.println(result);
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (ExecutionException e) {
// e.printStackTrace();
// }
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
MyThread thread3 = new MyThread();
MyThread thread4 = new MyThread();
// 单线程线程池
// ExecutorService executorService = Executors.newSingleThreadExecutor();
// executorService.execute(thread1);
// executorService.execute(thread2);
// 固定大小线程池
// ExecutorService executorService = Executors.newFixedThreadPool(2);
// executorService.execute(thread1);
// executorService.execute(thread2);
// executorService.execute(thread3);
// executorService.execute(thread4);
// 无限线程池
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(thread1);
executorService.execute(thread2);
executorService.execute(thread3);
executorService.execute(thread4);
executorService.shutdown();
}
}