Answer the question
In order to leave comments, you need to log in
Why doesn't the join() method work on my thread?
I need to calculate a complex mathematical expression, so I made it a decomposition to split its calculation into different threads.
I have thread #1 and thread #3. In thread #1 I calculate y1 = A*b and in thread #3 I calculate Y3 = A2C2-B2A2. After that I want to pass Y3 to thread #1 to compute Y3y1. In order to wait until thread number 3 completes, I called the thread3.join() method in the first thread, but for some reason it does not work for me and, as a result, NullPointerException pops up during the calculation of Y3y1. If I just put thread #1 to sleep for a few seconds before passing Y3 to it, then everything works fine. So why doesn't the join method work for me? And can you give recommendations on solving the problem and writing code for it?
Here is part of my code
thread1 = new Thread(
new Runnable() {
@Override
public void run() {
b = calc_b();
matrixA = generateMatrixA(matrixOrder);
y1 = calc_y1(matrixA, matrixOrder);
// Не работает!
try {
thread3.join();
} catch (Exception e) {
}
// Если сделаю так, то работает.
// try {
// thread1.sleep(4000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
Y3new = Y3;
calc_Y3y1(Y3new, y1, matrixOrder);
}
}
);
thread3 = new Thread(
new Runnable() {
@Override
public void run() {
matrixA2 = generateMatrixA2(matrixOrder);
matrixB2 = generateMatrixB2(matrixOrder);
matrixC = generateMatrixC(matrixOrder);
Y3 = calc_Y3(matrixA2, matrixB2, matrixC, matrixOrder);
}
}
);
thread1.start();
thread3.start();
Answer the question
In order to leave comments, you need to log in
You just write the variable Y3
in the stream thread3
and you just read it in the stream thread1
- that's the error.
Read something about Java concurrency and parallel computing in general - these are quite complex topics, and the difficulty here, of course, is not in calling a lot of new Thread ().
Perhaps in your case it will be easier to build logic on the actor model (there are many different implementations in java, although this is done more beautifully in scala). If you study multithreading from scratch, it will be easier to learn and more promising to use than classical approaches.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question