I am building a multi-threaded project in Java, I have entities and DAO packages to wrap the database tables and manipulating them. I have processing package which contains Runnables. The way i have implemented the Runnables so far is like this:
Class Thread1 implements Runnable{
Thread t;
parameters
...
public Thread1(){
t = new Thread(this,"Thread1");
....
t.start();
}
public int method1(){
...
return x;
}
public double method2(){
...
return y;
}
public void run(){
// some processing using DAO methods
....
method1();
...
method2();
...
}
}
The code works this way, but i need to use the same processing in the run() method as part of the processing in Thread2 class. The way i have structured my code does not allow to reuse the code. what would be a better structure to resolve this?
You could either:
Thread1andThread2extend the same abstract base class, and move shared logic to the parent (inheritance).Runnable, and implementrun()there (composition).You should always favour composition over inheritance, so the second option is usually better, because it also gives you the flexibility of changing behaviour at runtime.
For example:
Create a shared interface first
Make both classes implement it:
public class Thread1 implements SharedTaskandpublic class Thread2 implements SharedTask.Elsewhere in your code:
new Worker().start();