Advertisement
Guest User

ParallelCounter

a guest
Jun 24th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1. /*
  2.  *       File:  ParallelCounter.java
  3.  * Created on:  12.06.2018
  4.  * Created by:  Cavvar
  5.  *    Package:  edu.hm.cavvar.thread_examples;
  6.  *    Project:  SE_2
  7.  */
  8. package edu.hm.cavvar.thread_examples;
  9.  
  10. public class ParallelCounter {
  11.  
  12.     public static int count = 0;
  13.     public static final Object MONITOR = new Object();
  14.  
  15.     static class Incrementer extends Thread {
  16.  
  17.         private int myOwnCounter;
  18.  
  19.         @Override
  20.         public void run() {
  21.             for (int i = 0; i < 1000000; i++) {
  22.                 myOwnCounter++;
  23.                 synchronized (MONITOR) {
  24.                     count++;
  25.                 }
  26.             }
  27.         }
  28.  
  29.     }
  30.  
  31.     public static void main(String[] args) throws InterruptedException {
  32.         Thread thread1 = new Incrementer();
  33.         Thread thread2 = new Incrementer();
  34.  
  35.         thread1.start();
  36.         thread2.start();
  37.         System.out.println(thread1.isAlive());
  38.         thread1.join();
  39.         System.out.println(thread1.isAlive());
  40.         thread2.join();
  41.  
  42.         System.out.println(ParallelCounter.count);
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement