2
2
|
I have a Java class that starts up 2 separate threads. The first thread starts up fine and all the variables are correct.
When I start the second thread the global variables from thread one changes to the values set in thread 2.
I have tried adding synchronized blocks where the global variables are updated, but this did not work.
Is there a way to solve this issue? I want each thread to start up and use its own values without interference in other thread values.
EDIT:
Snippet of my Thread class:
| |||
add comment |
3
|
Static variables are shared between all Threads, thats what makes them static. If you want to use different values, either use ThreadLocals or (much better), use different objects with non-static variables in the differrent threads. Without further code it's difficult to say more though.
| ||||
5
|
Synchronisation merely controls the threads' access to the shared state.
If you want separate state per thread then you need to either declare different instances of that information (e.g. classes) per thread. e.g. simply instantiate a new object in each
Thread 's run() method, or perform a copy of the structure in question (e.g. a deep copy of a collection)
An alternative is to investigate ThreadLocal, in which each Thread will have a different copy of a nominated resource.
| ||
add comment |
static
that you may have used – no_answer_not_upvoted May 29 at 8:18