java多线程在java编程过程中有很多的用处,面试的时候也经常被问到,这里就线程池做一个简单的例子:通过线程池操作User,代码如下
1、实体类:User
package com.entity; //实体类 public class User { private int id ; private String name; private String age; private String address; public User(){ } public User(String name,String age,String address){ this.name = name; this.age = age; this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
2、数据库操类:UserDao
package com.dao; import com.entity.User; public class UserDao { //添加用户 public void addUser(User user){ //这个方法用来操作数据,代码省,做简单的输出 System.out.println(user.getName()); System.out.println(user.getAge()); } }
3、测试调用类:UserServer
package com.serverlet; import com.entity.User; import com.thread.ThreadPool; import com.thread.UserAddThread; /** * 用户操作类,线程池测试 */ public class UserServer { //添加用户 public void addUser() throws Exception{ User entity = new User("熊敏","28","深圳"); //将用户信息塞到线程池 ThreadPool.getInstance().execute(new UserAddThread(entity)); } //测试 public static void main(String[] args) throws Exception { UserServer userServer = new UserServer(); for (int i = 0; i < 10; i++) { userServer.addUser(); } } }
4、线程池类:ThreadPool
package com.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 实现线程池,的方法 */ public class ThreadPool { //JDK工具类,创建一个线程池,这个线程池最大的链接数为10 final ExecutorService exec = Executors.newFixedThreadPool(10); private static ThreadPool pool = new ThreadPool(); private ThreadPool(){ } public static ThreadPool getInstance(){ if(pool == null){ return pool = new ThreadPool(); } return pool; } /** * 执行线程任务 * @param command 一个需要执行的线程任务 */ public void execute(Runnable command) throws Exception{ exec.submit(command); } }
5、线程类(线程任务类):UserAddThread
package com.thread; import com.dao.UserDao; import com.entity.User; //线程类 public class UserAddThread implements Runnable{ UserDao userDao = new UserDao(); private User user; //初始化时,需要将user也实例化 public UserAddThread(User user){ this.user = user; } //执行任务 @Override public void run() { try{ userDao.addUser(user); }catch(Exception e){ e.printStackTrace(); } } }
完整例子见附件。