diff --git a/HW_Multithreading/src/Counter.java b/HW_Multithreading/src/Counter.java index c310ca7..a87fd07 100644 --- a/HW_Multithreading/src/Counter.java +++ b/HW_Multithreading/src/Counter.java @@ -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; } } diff --git a/HW_Multithreading/src/Main.java b/HW_Multithreading/src/Main.java index 7046417..41abda6 100644 --- a/HW_Multithreading/src/Main.java +++ b/HW_Multithreading/src/Main.java @@ -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(); + t2.join(); + + + System.out.println(count.getCountValue()+ " value from Main"); + } } diff --git a/HW_Multithreading/src/MyThread.java b/HW_Multithreading/src/MyThread.java new file mode 100644 index 0000000..7ee4867 --- /dev/null +++ b/HW_Multithreading/src/MyThread.java @@ -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"); + } + + + }*/ + + } +}