Running a task in parallel to another task

后端 未结 5 692
清歌不尽
清歌不尽 2020-12-10 09:23

I have the following Foo class that uses FooProcessor class. So what i want to do is, while running cp1 instance process method, in parallel I want

5条回答
  •  清歌不尽
    2020-12-10 10:07

    If you're writing your own standalone application, using threads might be the easiest way forward. If you're in a Java EE environment, you should not create your own Thread objects, but use some other mechanism (such as sending messages and have message listeners process the signals you send). This is to have the Java EE container control resource utilization such as thread pools.

    Example of using Threads:

    Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
             executeSomeCodeInP1();
        }
    });
    
    Thread t2 = new Thread(new Runnable() {
        @Override
        public void run() {
             executeSomeCodeInP2();
        }
    });
    
    t1.start();
    t2.start();
    
    // if you want to wait for both threads to finish before moving on, 
    // "join" the current thread
    t1.join();
    t2.join();
    

提交回复
热议问题