Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions HW_Multithreading/src/Counter.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ public Counter(int count) {
this.count = count;
}

public void increment(){
public synchronized void increment(){
count ++;
}

public void decrement(){
public synchronized void decrement(){
count --;
}

public int getCountValue(){
public int getCountValue(){
return count;
}
}
33 changes: 33 additions & 0 deletions HW_Multithreading/src/Main.java
Original file line number Diff line number Diff line change
@@ -1,2 +1,35 @@
public class Main {
public static void main(String[] args) throws InterruptedException {

Counter count=new Counter(0);



Runnable myThread1 = ()->{
for (int i = 0; i <10 ; i++) {
count.increment();
System.out.println(count.getCountValue()+ " value from increment");
}

};
myThread1.run();
Thread t1=new Thread(myThread1);
t1.start();

Runnable myThread2=()->{
for (int i = 0; i <10 ; i++){
count.decrement();
System.out.println(count.getCountValue()+ " value from decrement");
}
};
myThread2.run();
Thread t2=new Thread(myThread2);
t2.start();

t1.join();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is wrong: main thread is waiting for the t1 to finish and only then you start t2. We need 2 threads started almost simultaneously. So, you do not have 2 threads competing for the same Counter instance and you will always get correct result (0) because threads run in a sequence, not in parallel.

t2.join();


System.out.println(count.getCountValue()+ " value from Main");
}
}
28 changes: 28 additions & 0 deletions HW_Multithreading/src/MyThread.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
public class MyThread implements Runnable {
private Counter count;
// Thread t;

public MyThread(Counter count) {
this.count = count;
/* t=new Thread();
t.start();*/
}


@Override
public void run() {
/*for (int i = 0; i <10 ; i++) {
if (count.getCountValue() == 0) {
count.increment();
System.out.println(count.getCountValue()+ " value from increment");

} else {
count.decrement();
System.out.println(count.getCountValue()+ " value from decrement");
}


}*/

}
}