How to deal with multiple threads in one class?

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

    Two anonymous inner classes, like Thorbjørn Ravn Andersen suggested vaguely above, works. Here is a code example:

    public class OnlineResourceAdapter {
    
        public final Runnable typeA;
        public final Runnable typeB;
    
        public OnlineResourceAdapter() {
            typeA = new Runnable() {
                public void run() {
                    OnlineResourceAdapter.this.getInformationOfTypeA();
                }
            };
            typeB = new Runnable() {
                public void run() {
                    OnlineResourceAdapter.this.getInformationOfTypeB();
                    // one can use a non-final typed variable
                    // to store, which then<1>
                }
            };
        }
    
        public static void main(String args[]) {
            OnlineResourceAdapter x = new OnlineResourceAdapter();
            new Thread(x.typeA).start(); // start A
            new Thread(x.typeB).start(); // start B
            // <1>can be accessed here.
        }
    
        public void getInformationOfTypeA(){
            // get information of type A
            // return the data or directly store in OnlineResourceAdapter.
        }
    
        public void getInformationOfTypeB(){
            //get information of type B
        }
    
    }
    

    Edit: Yes, you're proposed way is a good way. You can even make the methods static. You can use "OnlineResourceAdapter.this." to access other variables to store results in.

提交回复
热议问题