I have been following several YouTube demos and tutorials on implementing multi-threaded operations in Java. However, all the tutorials show this following procedure:
class Task implements Runnable {
@Override
public void run() {
doTask();
}
public void doTask() {
for (int i = 0; i < 1500; i++) {
System.out.print('T');
}
}
}
public class Main {
public static void main(String[] args) {
Task t = new Task();
Thread thread = new Thread(t);
thread.start();
for (int i = 0; i < 1500; i++) {
System.out.print('M');
}
}
}
Some demos extends Thread class instead of Runnable, however, they follow a similar concept.
However, one problem that I reckon is that what if I want to have multiple logics in a class that I want to run concurrently, then, I have a issue. Well, Java veterans may know some trick to do so. However, I tried to implement such logic in a different way. Here is the code that I wrote:
class Task {
public void doTask() {
for (int i = 0; i < 1500; i++) {
System.out.print('T');
}
}
}
public class Main {
public static void main(String[] args) {
Task t = new Task();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
t.doTask();
}
});
thread.start();
for (int i = 0; i < 1500; i++) {
System.out.print('M');
}
}
}
Now, I can launch several threads and call the particular method that I want run concurrently.
Now, I want to know is there any benefit of implementing multi threaded operation using the first approach and is there any shortcomings of the latter one?