如何在java应用程序中实现多线程

时间:2015-10-29 06:01:31

标签: java multithreading

我正在使用方法callWapper

    public void callWrapper{
       setUnreadReceiptCount(wrapper.getWorkFlowCount(us, "unread", "receipt",Constants.Open));

       setWorklistFilesCount(wrapper.getWorkFlowCount(us, "unread", "file","worklist"));
    }

但是,我想在两个不同的线程中实现这两个调用。    我实现了run方法如下

   public void run(){
     Map session = ActionContext.getContext().getSession();
     UserSession us=(UserSession)session.get("user");
     try{
      if (t.getName().equals ("UnreadReceiptCount")){

      setUnreadReceiptCount(wrapper.getWorkFlowCount(us, "unread", "receipt",Constants.Open));  

        }
     if (t.getName().equals ("UnreadFileCount")){

     setWorklistFilesCount(wrapper.getWorkFlowCount(us, "unread", "file","worklist"));

      }
    }catch(EGOVException e){
        log.info(e.toString());
    }
 }

但是,这里的代码在获取userSession对象后没有执行。无法理解为什么?

我是新手,所以请告诉我是否正在做正确的事情

1 个答案:

答案 0 :(得分:0)

您可以按如下方式在2个不同的线程中实现2个方法调用(请参阅内联注释):

public void callWrapper{
    Map session = ActionContext.getContext().getSession();
    final UserSession us=(UserSession)session.get("user");
  //defining thread 1
     Thread t1 =  new Thread(new Runnable(){

            public void run() {
                 // calling first method
                    setUnreadReceiptCount(wrapper.getWorkFlowCount(us, "unread", "receipt",Constants.Open));

            }});
        //defining thread 2
        Thread t2 =  new Thread(new Runnable(){

            public void run() {
                     // calling second method
                    setWorklistFilesCount(wrapper.getWorkFlowCount(us, "unread", "file","worklist"));

            }});

        t1.start();// starting thread 1
        t2.start();// starting thread 1

         // if you want to wait the current execution until both threads finish
         // you can join them as below.
        t1.join();
        t2.join();
}

<强>更新

根据您的评论,如果您想使用您的代码没有问题,只需更改以下内容:

public void callWrapper{
        Map session = ActionContext.getContext().getSession();
        final UserSession us=(UserSession)session.get("user");
      //defining thread 1
         Thread t1 =  new Thread(this,"UnreadReceiptCount");


     //defining thread 2
         Thread t2 =  new Thread(this,"UnreadFileCount");   


            t1.start();// starting thread 1
            t2.start();// starting thread 1

             // if you want to wait the current execution until both threads finish
             // you can join them as below.
            t1.join();
            t2.join();
    }

并在run()方法中将t.getName()条件中的主题名称检查Thread.currentThread().getName()更改为if