Synchronisation of a counter
I try to learn something about multithreading and tried myself on a multithreaded counter. For my knowledge, I synchronized the counter variables but I encounter the following problems:
- The threads do not take alternating turns
- The counter does not count as intended (eg from 337 to 339 or from 344 to 344)
Can anyone please explain, what I did wrong?
Class RunThreads
public class RunThreads {
public static void main(String args) {
Thread thread1 = new Thread1();
Thread thread2 = new Thread2();
thread1.start();
thread2.start();
}
}
Class Thread1
public class Thread1 extends Thread {
public void run(){
while (ThreadCount.counter < 1000){
ThreadCount.incrementCounter();
ThreadCount.printCounter(this);
try{
notifyAll();
wait();
}
catch (Exception e){}
}
}
}
class Thread2 (Yes I don't need two separate classes but it makes it easier for me to understand)
public class Thread2 extends Thread {
public void run(){
while (ThreadCount.counter < 1000){
ThreadCount.incrementCounter();
ThreadCount.printCounter(this);
try{
notifyAll();
wait();
}
catch (Exception e){}
}
}
}
class ThreadCount
public class ThreadCount {
public static int counter = 0;
public static synchronized void incrementCounter(){
counter++;
}
public static void decrementCounter(){
counter--;
}
public static synchronized void printCounter(Thread t){;
Output.append(t.getName() + ":" + counter + "n");
}
}
class Output
public class Output{
public static String value = "";
public static synchronized void append(String s) {
value+=s;
}
}
java
add a comment |
I try to learn something about multithreading and tried myself on a multithreaded counter. For my knowledge, I synchronized the counter variables but I encounter the following problems:
- The threads do not take alternating turns
- The counter does not count as intended (eg from 337 to 339 or from 344 to 344)
Can anyone please explain, what I did wrong?
Class RunThreads
public class RunThreads {
public static void main(String args) {
Thread thread1 = new Thread1();
Thread thread2 = new Thread2();
thread1.start();
thread2.start();
}
}
Class Thread1
public class Thread1 extends Thread {
public void run(){
while (ThreadCount.counter < 1000){
ThreadCount.incrementCounter();
ThreadCount.printCounter(this);
try{
notifyAll();
wait();
}
catch (Exception e){}
}
}
}
class Thread2 (Yes I don't need two separate classes but it makes it easier for me to understand)
public class Thread2 extends Thread {
public void run(){
while (ThreadCount.counter < 1000){
ThreadCount.incrementCounter();
ThreadCount.printCounter(this);
try{
notifyAll();
wait();
}
catch (Exception e){}
}
}
}
class ThreadCount
public class ThreadCount {
public static int counter = 0;
public static synchronized void incrementCounter(){
counter++;
}
public static void decrementCounter(){
counter--;
}
public static synchronized void printCounter(Thread t){;
Output.append(t.getName() + ":" + counter + "n");
}
}
class Output
public class Output{
public static String value = "";
public static synchronized void append(String s) {
value+=s;
}
}
java
Adding some sample output would help give readers more context as to what exactly is happening.
– Garreth Golding
Nov 25 '18 at 19:51
Why does having two separate classes make it easier to understand? I ask because if you're confused between classes and instances - which it seems you are - you are a long way from getting to concurrency. I strongly suggest you get a good grip on the basics before moving onto advanced topics.
– Boris the Spider
Nov 25 '18 at 20:16
add a comment |
I try to learn something about multithreading and tried myself on a multithreaded counter. For my knowledge, I synchronized the counter variables but I encounter the following problems:
- The threads do not take alternating turns
- The counter does not count as intended (eg from 337 to 339 or from 344 to 344)
Can anyone please explain, what I did wrong?
Class RunThreads
public class RunThreads {
public static void main(String args) {
Thread thread1 = new Thread1();
Thread thread2 = new Thread2();
thread1.start();
thread2.start();
}
}
Class Thread1
public class Thread1 extends Thread {
public void run(){
while (ThreadCount.counter < 1000){
ThreadCount.incrementCounter();
ThreadCount.printCounter(this);
try{
notifyAll();
wait();
}
catch (Exception e){}
}
}
}
class Thread2 (Yes I don't need two separate classes but it makes it easier for me to understand)
public class Thread2 extends Thread {
public void run(){
while (ThreadCount.counter < 1000){
ThreadCount.incrementCounter();
ThreadCount.printCounter(this);
try{
notifyAll();
wait();
}
catch (Exception e){}
}
}
}
class ThreadCount
public class ThreadCount {
public static int counter = 0;
public static synchronized void incrementCounter(){
counter++;
}
public static void decrementCounter(){
counter--;
}
public static synchronized void printCounter(Thread t){;
Output.append(t.getName() + ":" + counter + "n");
}
}
class Output
public class Output{
public static String value = "";
public static synchronized void append(String s) {
value+=s;
}
}
java
I try to learn something about multithreading and tried myself on a multithreaded counter. For my knowledge, I synchronized the counter variables but I encounter the following problems:
- The threads do not take alternating turns
- The counter does not count as intended (eg from 337 to 339 or from 344 to 344)
Can anyone please explain, what I did wrong?
Class RunThreads
public class RunThreads {
public static void main(String args) {
Thread thread1 = new Thread1();
Thread thread2 = new Thread2();
thread1.start();
thread2.start();
}
}
Class Thread1
public class Thread1 extends Thread {
public void run(){
while (ThreadCount.counter < 1000){
ThreadCount.incrementCounter();
ThreadCount.printCounter(this);
try{
notifyAll();
wait();
}
catch (Exception e){}
}
}
}
class Thread2 (Yes I don't need two separate classes but it makes it easier for me to understand)
public class Thread2 extends Thread {
public void run(){
while (ThreadCount.counter < 1000){
ThreadCount.incrementCounter();
ThreadCount.printCounter(this);
try{
notifyAll();
wait();
}
catch (Exception e){}
}
}
}
class ThreadCount
public class ThreadCount {
public static int counter = 0;
public static synchronized void incrementCounter(){
counter++;
}
public static void decrementCounter(){
counter--;
}
public static synchronized void printCounter(Thread t){;
Output.append(t.getName() + ":" + counter + "n");
}
}
class Output
public class Output{
public static String value = "";
public static synchronized void append(String s) {
value+=s;
}
}
java
java
asked Nov 25 '18 at 19:46
gutenmorgenuhugutenmorgenuhu
1,62311228
1,62311228
Adding some sample output would help give readers more context as to what exactly is happening.
– Garreth Golding
Nov 25 '18 at 19:51
Why does having two separate classes make it easier to understand? I ask because if you're confused between classes and instances - which it seems you are - you are a long way from getting to concurrency. I strongly suggest you get a good grip on the basics before moving onto advanced topics.
– Boris the Spider
Nov 25 '18 at 20:16
add a comment |
Adding some sample output would help give readers more context as to what exactly is happening.
– Garreth Golding
Nov 25 '18 at 19:51
Why does having two separate classes make it easier to understand? I ask because if you're confused between classes and instances - which it seems you are - you are a long way from getting to concurrency. I strongly suggest you get a good grip on the basics before moving onto advanced topics.
– Boris the Spider
Nov 25 '18 at 20:16
Adding some sample output would help give readers more context as to what exactly is happening.
– Garreth Golding
Nov 25 '18 at 19:51
Adding some sample output would help give readers more context as to what exactly is happening.
– Garreth Golding
Nov 25 '18 at 19:51
Why does having two separate classes make it easier to understand? I ask because if you're confused between classes and instances - which it seems you are - you are a long way from getting to concurrency. I strongly suggest you get a good grip on the basics before moving onto advanced topics.
– Boris the Spider
Nov 25 '18 at 20:16
Why does having two separate classes make it easier to understand? I ask because if you're confused between classes and instances - which it seems you are - you are a long way from getting to concurrency. I strongly suggest you get a good grip on the basics before moving onto advanced topics.
– Boris the Spider
Nov 25 '18 at 20:16
add a comment |
3 Answers
3
active
oldest
votes
This demonstrates the pitfalls of swallowing exceptions. If you caught the exceptions in your threads and simply output them, you would observe the following:
java.lang.IllegalMonitorStateException
at java.base/java.lang.Object.notifyAll
at Thread2.run
This will happen when you call wait
and notify
/notifyAll
on an object (the Thread
objects, in this case) where you don't hold the lock by means of synchronized
.
If you create a common object that both threads synchronize on, and call wait
/notifyAll
on, you will get what you are observing. For example:
class Thread1 extends Thread {
public void run(){
synchronized (ThreadCount.lockObj) {
while (ThreadCount.counter < 1000) {
ThreadCount.incrementCounter();
ThreadCount.printCounter(this);
try {
ThreadCount.lockObj.notifyAll();
ThreadCount.lockObj.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
Thanks. I got it now. I moved the try/catch block to the ThreadCount Object
– gutenmorgenuhu
Nov 25 '18 at 20:17
That works too. Don't forget to upvote and accept this answer if you found it helpful.
– Joe C
Nov 25 '18 at 20:24
add a comment |
The increment and the print are done in two separate operations.
So you can have (for example)
- thread1: increment from 342 to 343
- thread2: increment from 343 to 344
- thread2: print 344
- thread1: print 344
Regarding the alternating turns: both threads call wait() and notifyAll() on themselves (so, on two separate objects), and do so without holding their lock, which throws an exception. And since you ignore exceptions, you can't notice the error you made. Never ignore exceptions. Do not catch Exception.
To have alternating turns, the incrementCounter()
method could look like this:
private static boolean turn;
public static synchronized void incrementCounter(){
counter++;
printCounter(Thread.currentThread());
turn = !turn;
boolean nextTurn = !turn;
ThreadCount.class.notifyAll();
while (turn != nextTurn) {
try {
ThreadCount.class.wait();
}
catch (InterruptedException e) {
return;
}
}
}
The turn boolean and the while loop might look averkill, but they're in fact necessary if you want your code to work as expected even in case of spurious wakeups.
So calling the printCounter method from within the incrementCounter method should work?
– gutenmorgenuhu
Nov 25 '18 at 19:56
It would make sure that you don't print duplicates and don't have holes in the sequence. But it won't ensure alternating turns.
– JB Nizet
Nov 25 '18 at 19:57
Okay. Thanks: Halfway there then: How can I get the turns?
– gutenmorgenuhu
Nov 25 '18 at 19:58
add a comment |
*Thread1* ThreadCount.incrementCounter();
*Thread2* ThreadCount.incrementCounter();
*Thread1* ThreadCount.printCounter(this);
*Thread2* ThreadCount.printCounter(this);
In this action Thread 1 increment by 2 and Thread2 increment by 0.
You can use AtomicInteger etc for thread-safe operations.
You should encapsulate int. Don't leave public.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53471232%2fsynchronisation-of-a-counter%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
This demonstrates the pitfalls of swallowing exceptions. If you caught the exceptions in your threads and simply output them, you would observe the following:
java.lang.IllegalMonitorStateException
at java.base/java.lang.Object.notifyAll
at Thread2.run
This will happen when you call wait
and notify
/notifyAll
on an object (the Thread
objects, in this case) where you don't hold the lock by means of synchronized
.
If you create a common object that both threads synchronize on, and call wait
/notifyAll
on, you will get what you are observing. For example:
class Thread1 extends Thread {
public void run(){
synchronized (ThreadCount.lockObj) {
while (ThreadCount.counter < 1000) {
ThreadCount.incrementCounter();
ThreadCount.printCounter(this);
try {
ThreadCount.lockObj.notifyAll();
ThreadCount.lockObj.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
Thanks. I got it now. I moved the try/catch block to the ThreadCount Object
– gutenmorgenuhu
Nov 25 '18 at 20:17
That works too. Don't forget to upvote and accept this answer if you found it helpful.
– Joe C
Nov 25 '18 at 20:24
add a comment |
This demonstrates the pitfalls of swallowing exceptions. If you caught the exceptions in your threads and simply output them, you would observe the following:
java.lang.IllegalMonitorStateException
at java.base/java.lang.Object.notifyAll
at Thread2.run
This will happen when you call wait
and notify
/notifyAll
on an object (the Thread
objects, in this case) where you don't hold the lock by means of synchronized
.
If you create a common object that both threads synchronize on, and call wait
/notifyAll
on, you will get what you are observing. For example:
class Thread1 extends Thread {
public void run(){
synchronized (ThreadCount.lockObj) {
while (ThreadCount.counter < 1000) {
ThreadCount.incrementCounter();
ThreadCount.printCounter(this);
try {
ThreadCount.lockObj.notifyAll();
ThreadCount.lockObj.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
Thanks. I got it now. I moved the try/catch block to the ThreadCount Object
– gutenmorgenuhu
Nov 25 '18 at 20:17
That works too. Don't forget to upvote and accept this answer if you found it helpful.
– Joe C
Nov 25 '18 at 20:24
add a comment |
This demonstrates the pitfalls of swallowing exceptions. If you caught the exceptions in your threads and simply output them, you would observe the following:
java.lang.IllegalMonitorStateException
at java.base/java.lang.Object.notifyAll
at Thread2.run
This will happen when you call wait
and notify
/notifyAll
on an object (the Thread
objects, in this case) where you don't hold the lock by means of synchronized
.
If you create a common object that both threads synchronize on, and call wait
/notifyAll
on, you will get what you are observing. For example:
class Thread1 extends Thread {
public void run(){
synchronized (ThreadCount.lockObj) {
while (ThreadCount.counter < 1000) {
ThreadCount.incrementCounter();
ThreadCount.printCounter(this);
try {
ThreadCount.lockObj.notifyAll();
ThreadCount.lockObj.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
This demonstrates the pitfalls of swallowing exceptions. If you caught the exceptions in your threads and simply output them, you would observe the following:
java.lang.IllegalMonitorStateException
at java.base/java.lang.Object.notifyAll
at Thread2.run
This will happen when you call wait
and notify
/notifyAll
on an object (the Thread
objects, in this case) where you don't hold the lock by means of synchronized
.
If you create a common object that both threads synchronize on, and call wait
/notifyAll
on, you will get what you are observing. For example:
class Thread1 extends Thread {
public void run(){
synchronized (ThreadCount.lockObj) {
while (ThreadCount.counter < 1000) {
ThreadCount.incrementCounter();
ThreadCount.printCounter(this);
try {
ThreadCount.lockObj.notifyAll();
ThreadCount.lockObj.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
answered Nov 25 '18 at 19:59
Joe CJoe C
11.6k62543
11.6k62543
Thanks. I got it now. I moved the try/catch block to the ThreadCount Object
– gutenmorgenuhu
Nov 25 '18 at 20:17
That works too. Don't forget to upvote and accept this answer if you found it helpful.
– Joe C
Nov 25 '18 at 20:24
add a comment |
Thanks. I got it now. I moved the try/catch block to the ThreadCount Object
– gutenmorgenuhu
Nov 25 '18 at 20:17
That works too. Don't forget to upvote and accept this answer if you found it helpful.
– Joe C
Nov 25 '18 at 20:24
Thanks. I got it now. I moved the try/catch block to the ThreadCount Object
– gutenmorgenuhu
Nov 25 '18 at 20:17
Thanks. I got it now. I moved the try/catch block to the ThreadCount Object
– gutenmorgenuhu
Nov 25 '18 at 20:17
That works too. Don't forget to upvote and accept this answer if you found it helpful.
– Joe C
Nov 25 '18 at 20:24
That works too. Don't forget to upvote and accept this answer if you found it helpful.
– Joe C
Nov 25 '18 at 20:24
add a comment |
The increment and the print are done in two separate operations.
So you can have (for example)
- thread1: increment from 342 to 343
- thread2: increment from 343 to 344
- thread2: print 344
- thread1: print 344
Regarding the alternating turns: both threads call wait() and notifyAll() on themselves (so, on two separate objects), and do so without holding their lock, which throws an exception. And since you ignore exceptions, you can't notice the error you made. Never ignore exceptions. Do not catch Exception.
To have alternating turns, the incrementCounter()
method could look like this:
private static boolean turn;
public static synchronized void incrementCounter(){
counter++;
printCounter(Thread.currentThread());
turn = !turn;
boolean nextTurn = !turn;
ThreadCount.class.notifyAll();
while (turn != nextTurn) {
try {
ThreadCount.class.wait();
}
catch (InterruptedException e) {
return;
}
}
}
The turn boolean and the while loop might look averkill, but they're in fact necessary if you want your code to work as expected even in case of spurious wakeups.
So calling the printCounter method from within the incrementCounter method should work?
– gutenmorgenuhu
Nov 25 '18 at 19:56
It would make sure that you don't print duplicates and don't have holes in the sequence. But it won't ensure alternating turns.
– JB Nizet
Nov 25 '18 at 19:57
Okay. Thanks: Halfway there then: How can I get the turns?
– gutenmorgenuhu
Nov 25 '18 at 19:58
add a comment |
The increment and the print are done in two separate operations.
So you can have (for example)
- thread1: increment from 342 to 343
- thread2: increment from 343 to 344
- thread2: print 344
- thread1: print 344
Regarding the alternating turns: both threads call wait() and notifyAll() on themselves (so, on two separate objects), and do so without holding their lock, which throws an exception. And since you ignore exceptions, you can't notice the error you made. Never ignore exceptions. Do not catch Exception.
To have alternating turns, the incrementCounter()
method could look like this:
private static boolean turn;
public static synchronized void incrementCounter(){
counter++;
printCounter(Thread.currentThread());
turn = !turn;
boolean nextTurn = !turn;
ThreadCount.class.notifyAll();
while (turn != nextTurn) {
try {
ThreadCount.class.wait();
}
catch (InterruptedException e) {
return;
}
}
}
The turn boolean and the while loop might look averkill, but they're in fact necessary if you want your code to work as expected even in case of spurious wakeups.
So calling the printCounter method from within the incrementCounter method should work?
– gutenmorgenuhu
Nov 25 '18 at 19:56
It would make sure that you don't print duplicates and don't have holes in the sequence. But it won't ensure alternating turns.
– JB Nizet
Nov 25 '18 at 19:57
Okay. Thanks: Halfway there then: How can I get the turns?
– gutenmorgenuhu
Nov 25 '18 at 19:58
add a comment |
The increment and the print are done in two separate operations.
So you can have (for example)
- thread1: increment from 342 to 343
- thread2: increment from 343 to 344
- thread2: print 344
- thread1: print 344
Regarding the alternating turns: both threads call wait() and notifyAll() on themselves (so, on two separate objects), and do so without holding their lock, which throws an exception. And since you ignore exceptions, you can't notice the error you made. Never ignore exceptions. Do not catch Exception.
To have alternating turns, the incrementCounter()
method could look like this:
private static boolean turn;
public static synchronized void incrementCounter(){
counter++;
printCounter(Thread.currentThread());
turn = !turn;
boolean nextTurn = !turn;
ThreadCount.class.notifyAll();
while (turn != nextTurn) {
try {
ThreadCount.class.wait();
}
catch (InterruptedException e) {
return;
}
}
}
The turn boolean and the while loop might look averkill, but they're in fact necessary if you want your code to work as expected even in case of spurious wakeups.
The increment and the print are done in two separate operations.
So you can have (for example)
- thread1: increment from 342 to 343
- thread2: increment from 343 to 344
- thread2: print 344
- thread1: print 344
Regarding the alternating turns: both threads call wait() and notifyAll() on themselves (so, on two separate objects), and do so without holding their lock, which throws an exception. And since you ignore exceptions, you can't notice the error you made. Never ignore exceptions. Do not catch Exception.
To have alternating turns, the incrementCounter()
method could look like this:
private static boolean turn;
public static synchronized void incrementCounter(){
counter++;
printCounter(Thread.currentThread());
turn = !turn;
boolean nextTurn = !turn;
ThreadCount.class.notifyAll();
while (turn != nextTurn) {
try {
ThreadCount.class.wait();
}
catch (InterruptedException e) {
return;
}
}
}
The turn boolean and the while loop might look averkill, but they're in fact necessary if you want your code to work as expected even in case of spurious wakeups.
edited Nov 25 '18 at 20:22
answered Nov 25 '18 at 19:54
JB NizetJB Nizet
543k588851011
543k588851011
So calling the printCounter method from within the incrementCounter method should work?
– gutenmorgenuhu
Nov 25 '18 at 19:56
It would make sure that you don't print duplicates and don't have holes in the sequence. But it won't ensure alternating turns.
– JB Nizet
Nov 25 '18 at 19:57
Okay. Thanks: Halfway there then: How can I get the turns?
– gutenmorgenuhu
Nov 25 '18 at 19:58
add a comment |
So calling the printCounter method from within the incrementCounter method should work?
– gutenmorgenuhu
Nov 25 '18 at 19:56
It would make sure that you don't print duplicates and don't have holes in the sequence. But it won't ensure alternating turns.
– JB Nizet
Nov 25 '18 at 19:57
Okay. Thanks: Halfway there then: How can I get the turns?
– gutenmorgenuhu
Nov 25 '18 at 19:58
So calling the printCounter method from within the incrementCounter method should work?
– gutenmorgenuhu
Nov 25 '18 at 19:56
So calling the printCounter method from within the incrementCounter method should work?
– gutenmorgenuhu
Nov 25 '18 at 19:56
It would make sure that you don't print duplicates and don't have holes in the sequence. But it won't ensure alternating turns.
– JB Nizet
Nov 25 '18 at 19:57
It would make sure that you don't print duplicates and don't have holes in the sequence. But it won't ensure alternating turns.
– JB Nizet
Nov 25 '18 at 19:57
Okay. Thanks: Halfway there then: How can I get the turns?
– gutenmorgenuhu
Nov 25 '18 at 19:58
Okay. Thanks: Halfway there then: How can I get the turns?
– gutenmorgenuhu
Nov 25 '18 at 19:58
add a comment |
*Thread1* ThreadCount.incrementCounter();
*Thread2* ThreadCount.incrementCounter();
*Thread1* ThreadCount.printCounter(this);
*Thread2* ThreadCount.printCounter(this);
In this action Thread 1 increment by 2 and Thread2 increment by 0.
You can use AtomicInteger etc for thread-safe operations.
You should encapsulate int. Don't leave public.
add a comment |
*Thread1* ThreadCount.incrementCounter();
*Thread2* ThreadCount.incrementCounter();
*Thread1* ThreadCount.printCounter(this);
*Thread2* ThreadCount.printCounter(this);
In this action Thread 1 increment by 2 and Thread2 increment by 0.
You can use AtomicInteger etc for thread-safe operations.
You should encapsulate int. Don't leave public.
add a comment |
*Thread1* ThreadCount.incrementCounter();
*Thread2* ThreadCount.incrementCounter();
*Thread1* ThreadCount.printCounter(this);
*Thread2* ThreadCount.printCounter(this);
In this action Thread 1 increment by 2 and Thread2 increment by 0.
You can use AtomicInteger etc for thread-safe operations.
You should encapsulate int. Don't leave public.
*Thread1* ThreadCount.incrementCounter();
*Thread2* ThreadCount.incrementCounter();
*Thread1* ThreadCount.printCounter(this);
*Thread2* ThreadCount.printCounter(this);
In this action Thread 1 increment by 2 and Thread2 increment by 0.
You can use AtomicInteger etc for thread-safe operations.
You should encapsulate int. Don't leave public.
answered Nov 25 '18 at 19:52
László TóthLászló Tóth
765
765
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53471232%2fsynchronisation-of-a-counter%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Adding some sample output would help give readers more context as to what exactly is happening.
– Garreth Golding
Nov 25 '18 at 19:51
Why does having two separate classes make it easier to understand? I ask because if you're confused between classes and instances - which it seems you are - you are a long way from getting to concurrency. I strongly suggest you get a good grip on the basics before moving onto advanced topics.
– Boris the Spider
Nov 25 '18 at 20:16