面试常问--线程的三种创建方式
1. 继承Thread类,重写run方法
1 class CreateThread extends Thread { 2 // run方法中编写 多线程需要执行的代码 3 publicvoid run() { 4 for (inti = 0; i< 10; i++) { 5 System.out.println("i:" + i); 6 } 7 } 8 } 9 public class ThreadDemo { 10 11 public static void main(String[] args) { 12 System.out.println("-----多线程创建开始-----"); 13 // 1.创建一个线程 14 CreateThread createThread = new CreateThread(); 15 // 2.开始执行线程 注意 开启线程不是调用run方法,而是start方法 16 System.out.println("-----多线程创建启动-----"); 17 createThread.start(); 18 System.out.println("-----多线程创建结束-----"); 19 } 20 21 }
2. 实现runnable接口,重写run方法
class CreateRunnable implements Runnable { @Override publicvoid run() { for (inti = 0; i< 10; i++) { System.out.println("i:" + i); } } } publicclass ThreadDemo2 { publicstaticvoid main(String[] args) { System.out.println("-----多线程创建开始-----"); // 1.创建一个线程 CreateRunnable createThread = new CreateRunnable(); // 2.开始执行线程 注意 开启线程不是调用run方法,而是start方法 System.out.println("-----多线程创建启动-----"); Thread thread = new Thread(createThread); thread.start(); System.out.println("-----多线程创建结束-----"); } }
3. 创建线程池
线程池提供了一个线程队列,队列中保存着所有等待状态的线程。避免了创建与销毁额外开销,提交了响应速度。
1 /*2、分组算法**/ 2 Map<String, List<TNormalPlansend>> tNormalPlansendMap = new HashMap<>(); 3 for (TNormalPlansend tNormalPlansend : newPlans) { 4 List<TNormalPlansend> tempList = tNormalPlansendMap.get(tNormalPlansend.getDeviceId()+""); 5 /*如果取不到数据,那么直接new一个空的ArrayList**/ 6 if (tempList == null) { 7 tempList = new ArrayList<>(); 8 tempList.add(tNormalPlansend); 9 tNormalPlansendMap.put(tNormalPlansend.getDeviceId()+"", tempList); 10 } 11 else { 12 /*某个deviceId之前已经存放过了,则直接追加数据到原来的List里**/ 13 tempList.add(tNormalPlansend); 14 tNormalPlansendMap.put(tNormalPlansend.getDeviceId()+"", tempList); 15 } 16 17 } 18 19 /*3、遍历map,验证结果**/ 20 // for(String deviceId : tNormalPlansendMap.keySet()){ 21 // System.out.println("0000000000000==============" + tNormalPlansendMap.get(deviceId)); 22 // } 23 System.out.println("0000000000000开始线程处理入库==============" ); 24 25 // 开启的线程数 26 int runSize = tNormalPlansendMap.size(); 27 // 创建一个线程池,数量和开启线程的数量一样 28 ExecutorService executor = Executors.newFixedThreadPool(runSize); 29 // 创建两个个计数器 30 for(String deviceId : tNormalPlansendMap.keySet()){ 31 List<TNormalPlansend> newList = tNormalPlansendMap.get(deviceId); 32 InsertDataThread thread = new InsertDataThread(newList,tNormalPlansendMapper); 33 executor.execute(thread); 34 } 35 executor.shutdown();
ps 面试题:
1.进程与线程的区别?
答:进程是所有线程的集合,每一个线程是进程中的一条执行路径,线程只是一条执行路径。
2.为什么要用多线程?
答:提高程序效率
3.多线程创建方式?
答:继承Thread或Runnable 接口。
4.是继承Thread类好还是实现Runnable接口好?
答:Runnable接口好,因为实现了接口还可以继续继承。继承Thread类不能再继承。
5.你在哪里用到了多线程?
答:主要能体现到多线程提高程序效率。
举例:分批发送短信、迅雷多线程下载等。

浙公网安备 33010602011771号