java多线程怎么使主线程不用等待子线程执行完,就返回页面

Drink_SuanMeiTang 2017-12-11 10:06:01
新人求教了,在java后台中怎么使主线程不用等待子线程执行完,让主线程先走返回页面,我使用的接口实现的多线程,我现在的需求是主线程不用等待子线程执行完,先返回页面,让子线程在后台继续执行,小白,请教,谢谢各位了。
...全文
2048 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Drink_SuanMeiTang 2017-12-13
  • 打赏
  • 举报
回复
private synchronized int getQueueSize(Queue queue){ return queue.size(); }
Drink_SuanMeiTang 2017-12-13
  • 打赏
  • 举报
回复
private int index; public TaskThreadPool(int index){ this.index = index; } public void run(){ try{ Thread.sleep(3000); }catch (InterruptedException e){ e.printStackTrace(); } } 还是我把多人发送邮件写错地方了,小白请教了
Drink_SuanMeiTang 2017-12-13
  • 打赏
  • 举报
回复
ThreadPoolExecutor tpe = new ThreadPoolExecutor(5, 10, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(queueDeep),new ThreadPoolExecutor.DiscardOldestPolicy()); String[] r = rusers.split(","); // 向线程池中添加任务 for (int i = 0; i < r.length; i++){ try{ Thread.sleep(1); List<File> list = new ArrayList<File>(); //根据用户id查询用户邮箱 User u = User.dao.findFirst( "select user_email from oa_user where user_id=?", r[i]); //判断邮箱是否为空 if (u.getStr("user_email") != null) { //判断是否有文件 if (file != null) { list.add(fil); } int moticeid=notice.getInt("notice_id"); //调用工具类,发送 邮件 MailKit.send(u.getStr("user_email"), null,notice.getStr("notice_title"), getServerUrl("") + "/console/notice/views?notice_id="+ notice.getInt("notice_id"), list); } }catch (InterruptedException e){ e.printStackTrace(); } while (getQueueSize(tpe.getQueue()) >= queueDeep){ try{ Thread.sleep(3000); }catch (InterruptedException e){ e.printStackTrace(); } } TaskThreadPool ttp = new TaskThreadPool(i); tpe.execute(ttp); } tpe.shutdown(); 我使用了 synchronized将Queue同步了,还是我写的不对吗?
  • 打赏
  • 举报
回复
引用 1 楼 jkl012789 的回复:
主线程本身就不会等待子线程执行完呀,它应该会在创建子线程后继续执行其他代码的呀,不会管子线程是否执行完毕。难道我们玩的不是同一款游戏?
估计他是设置了等待了吧。。。
叮咚呛咚呛 2017-12-11
  • 打赏
  • 举报
回复
主线程本身就不会等待子线程执行完呀,它应该会在创建子线程后继续执行其他代码的呀,不会管子线程是否执行完毕。难道我们玩的不是同一款游戏?
X元素 2017-12-11
  • 打赏
  • 举报
回复
看看伪代码
main{
  //主线程去干自己的事
  Object  result = ServiceA.doSomeThing();
  new Thread(){
    public void run(){
      //子线程去干自己的事情
    }
  }.start()
  return result ;
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧