creating threads through annomyous inner class

后端 未结 3 888
情深已故
情深已故 2021-02-10 09:25

I was developing the code of creating a thread but without extending the thread class or implementing the runnable interface , that is through anonymous inner classes ..

3条回答
  •  悲&欢浪女
    2021-02-10 09:54

    The fact that you declare two anonymous inner classes extending Thread and overriding the run() method is not an issue in itself. We may consider not really readable but there is no issue.

    However, you should consider using the Runnable interface. You should separate the processing/algorithms and the Threading policy. So it would be better to have something like this:

    public class ThreadLauncher {
        public static void main(String[] args) {
             Thread job1 = new Thread(new Job1());
             Thread job2 = new Thread(new Job2());
             job1.start();
             job2.start();
        }
    }
    
    public class Job1 implements Runnable {
        @Override
        public void run() {
             // Do some stuff
        }
    }
    
    public class Job2 implements Runnable {
        @Override
        public void run() {
             // Do some other stuff
        }
    }
    

    This allows you to launch several time the same job, for example.

    If you want to take it one step further, you could consider using ThreadPoolExecutor to handle your Threading strategy.

提交回复
热议问题