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:
Thread1
and Thread2
extend the same abstract base class, and move shared logic to the parent (inheritance).Runnable
, and implement run()
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
public interface SharedTask {
public void method1();
public void method2();
}
Make both classes implement it:
public class Thread1 implements SharedTask
and public class Thread2 implements SharedTask
.
public class Worker implements Runnable {
public Worker (SharedTask task) {
this.task = task;
...
}
public void run() {
task.method1();
task.method2();
}
}
Elsewhere in your code:
new Worker().start();