I'm creating two different threads which will solve same problem with different ways and I will calculate their solving time. I've created a structure like that;
MainController.java
public static void main(String[] args) throws Exception {
MainController mc= new MainController();
mc.setProblem();
Thread1 thread1 = new Thread1("thread1",problem,approach1);
Thread2 thread2 = new Thread2("thread2",problem,approach2);
thread1.start();
thread2.start();
}
Thread1.java
class Thread1 implements Runnable{
public void run() {
System.out.println("Running " + threadName );
try {
solve(approach);
} catch (Exception e) {
System.out.println("Thread " + threadName + " interrupted.");
}
//showTable();
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
public void solve(approach) throws Exception {
// Throw an exception to stop the process if the puzzle is solved
if (didIsolve()) {//true if yes
System.out.println("----" + threadName +"----");
showResult();
System.out.println("--------------------------");
throw new Exception("ex");
}
}
}
Thread2.java is the same as above code block.
And output like
Creating thread1
Creating thread2
Starting thread1
Starting thread2
Running thread2
Running thread1
Thread thread1 exiting.
----thread2----
RESULT METHOD OUTPUT
--------------------------
Thread thread2 interrupted.
Thread thread2 exiting.
As you see above, thread1 did not solve problem, at least did not show result.
Also I've checked this topics so far
multiple threads performing different tasks
Java threads to do different tasks?
Edit:
Well, I think I found the problem. I changed MainController class;
public static void main(String[] args) throws Exception {
MainController mc= new MainController();
mc.setProblem();
MainController mc2 = new MainContoller();
mc1.setProblem();
Thread1 thread1 = new Thread1("thread1",mc.problem,approach1);
Thread2 thread2 = new Thread2("thread2",mc1.problem,approach2);
thread1.start();
thread2.start();
}
And it worked, but I don't know why. I will not accept my answer as correct answer for few days, may someone explain this situation?