How to deal with multiple threads in one class?

后端 未结 6 1260
醉酒成梦
醉酒成梦 2021-02-04 12:31

Threads are often designed in two ways (see java tutorials): either by extending the Thread class or by implementing the Runnable class. Either way, you need to specify what wil

6条回答
  •  深忆病人
    2021-02-04 13:11

    Use anonymous classes of type Callable (which, in contrast to Runnable, can return values) and execute them using an Executor. If the logic to retrieve informationA and informationB is very similar, you may of course refactor that and use a single, parameterizes inner class of Callables.

    I'm not sure if Callable and Executor are part of J2ME spec though. In standard Java, i'd go for a Proxy approach anyway and encapsulate the external resource as interface.

    public class AsyncMethodsTest {
    
        public class OnlineResourceAdapter {
    
            private final ExecutorService executor = Executors.newFixedThreadPool(2);
    
            public String getInformationOfTypeA() throws InterruptedException, ExecutionException,
                    TimeoutException {
                Callable callable = new Callable() {
                    @Override
                    public String call() throws Exception {
                        // Connect to external resource
                        Thread.sleep(500);
                        return "A";
                    }
    
                };
                Future submit = executor.submit(callable);
                return submit.get(1000, TimeUnit.MILLISECONDS);
            }
    
            public String getInformationOfTypeB() throws InterruptedException, ExecutionException,
                    TimeoutException {
                Callable callable = new Callable() {
                    @Override
                    public String call() throws Exception {
                        // Connect to external resource
                        Thread.sleep(1500);
                        return "B";
                    }
    
                };
                Future submit = executor.submit(callable);
                return submit.get(1000, TimeUnit.MILLISECONDS);
            }
    
        }
    
        @Test
        public void testMethodCalls() throws Exception {
            OnlineResourceAdapter adapter = new OnlineResourceAdapter();
            assertNotNull(adapter.getInformationOfTypeA());
            assertNotNull(adapter.getInformationOfTypeB());
        }
    }
    

提交回复
热议问题