Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ua.nure.rozdaybeda.Practice5.part3;
- import java.util.ArrayList;
- /**
- * Task 3
- * @author Oleg
- *
- */
- public class Part3 {
- /**
- * Demonstrates work of class
- * @param args Command line arguments
- */
- public static void main(String[] args) {
- ArrayList<Thread> threads = new ArrayList<Thread>();
- Counter counter = new Counter();
- for(int a = 0; a < 10; a++) {
- Thread current;
- threads.add(current = new Thread(() ->
- {
- for(int i = 0;i < 10; i++)
- counter.notSyncAccess();
- }
- ));
- current.start();
- }
- for(Thread t: threads) {
- try {
- t.join();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- threads.clear();
- // System.out.println("NEXT################################################");
- //
- // for(int a = 0; a < 10; a++) {
- // Thread current;
- // threads.add(current = new Thread(() ->
- // {
- // for(int i = 0;i < 10; i++)
- // counter.syncAccess();
- // }
- // ));
- // current.start();
- // }
- // for(Thread t: threads) {
- // try {
- // t.join();
- // } catch (InterruptedException e) {
- // e.printStackTrace();
- // }
- // }
- // threads.clear();
- System.out.println("c1 " + counter.c1 + " c2 " + counter.c2);
- }
- }
- package ua.nure.rozdaybeda.Practice5.part3;
- /**
- * Encapsulates two counters and provides synchronized and non-synchronized access
- * @author Oleg
- *
- */
- public class Counter{
- /**
- * Counter 1
- */
- volatile int c1 = 0;
- /**
- * Counter 2
- */
- volatile int c2 = 0;
- /**Compares counters and prints result then increments first counter and waits 10 milliseconds. Finally, increments secont counter.
- */
- public void compareAndChange() {
- // System.out.println(c1 == c2 ? "equals" : "not
- c1 += 1;
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- c2 += 1;
- }
- /**
- * Provides synchronized access to {@link #compareAndChange compareAndChange} method
- */
- public synchronized void syncAccess(){
- compareAndChange();
- }
- /**
- * Provides non-synchronized access to {@link #compareAndChange compareAndChanged} method
- */
- public void notSyncAccess() {
- compareAndChange();
- }
- }
Add Comment
Please, Sign In to add comment