How to deal with multiple threads in one class?

后端 未结 6 1261
醉酒成梦
醉酒成梦 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:23

    Many people have already suggested good methods of how to do this using several classes. Since you seem to prefer a way which doesn't require multiple classes, you might also want to consider using the constructor to give information about which resource to fetch:

    public class OnlineResourceAdapter implements Runnable
    {
        private string resourceType;
    
        public OnlineResourceAdapter(string resourceType)
        {
            this.resourceType = resourceType;
        }
    
        public void run() {
            if (resourceType.equals("A") {
                getInformationOfTypeA();
            } else {
                // etc..
            }
        }
    
        public void getInformationOfTypeA(){
            //get information of type A
        }
    
        public void getInformationOfTypeB(){
            //get information of type B
        }
    }
    

    Usage:

    (new Thread(new OnlineResourceAdapter("A"))).start();
    

提交回复
热议问题