Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. Java
  4. Threads in details

Threads in details

Scheduled Pinned Locked Moved Java
2 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • N Offline
    N Offline
    Neo10101
    wrote on last edited by
    #1

    See the following code: Unsafe Counter

    public class Counter implements Counting
    {
    private int value = 0;

    public int incrementAndGet()
    {
        return this.value++;
    }
    
    public int decrementAndGet()
    {
        return this.value--;
    }
    

    }

    CounterClient

    public class CounterClient implements Runnable
    {
    //shared data
    private Counting counter;

    public CounterClient(Counting counter)
    {
        this.counter = counter;
    }
    
    public void run()
    {
        while(true)
        {
            System.out.println("Incrementing from " + Thread.currentThread().getName() );                
            System.out.println("Counter value in " + Thread.currentThread().getName() + " = " + counter.incrementAndGet());                
            
            try
            {
                Thread.sleep(2000L);
            } catch (InterruptedException ex)
            {
                Logger.getLogger(CounterClient.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    

    }

    TestCounter

    public class TestCounter
    {
    public static void main(String args[])
    {
    Counter counter = new Counter();
    SafeCounter safeCounter = new SafeCounter();

        Executor exec = Executors.newCachedThreadPool();
        
        exec.execute(new CounterClient(counter));
        exec.execute(new CounterClient(counter));        
        /\*
        exec.execute(new CounterClient(safeCounter));
        exec.execute(new CounterClient(safeCounter));
         \*/
         
    }
    

    }

    I did a test run for this code and one of the outputs was this:

    Incrementing from pool-1-thread-1
    Incrementing from pool-1-thread-2
    Counter value in pool-1-thread-1 = 0
    Counter value in pool-1-thread-2 = 1
    Incrementing from pool-1-thread-2
    Incrementing from pool-1-thread-1
    Counter value in pool-1-thread-2 = 2
    Counter value in pool-1-thread-1 = 3
    Incrementing from pool-1-thread-2
    Incrementing from pool-1-thread-1
    Counter value in pool-1-thread-1 = 4
    Counter value in pool-1-thread-2 = 5
    Incrementing from pool-1-thread-2
    Incrementing from pool-1-thread-1
    Counter value in pool-1-thread-1 = 6
    Counter value in pool-1-thread-2 = 7
    Incrementing from pool-1-thread-1
    Counter value in pool-1-thread-1 = 8
    Incrementing from pool-1-thread-2
    Counter value in pool-1-thread-2 = 9
    Incrementing from pool-1-thread

    N 1 Reply Last reply
    0
    • N Neo10101

      See the following code: Unsafe Counter

      public class Counter implements Counting
      {
      private int value = 0;

      public int incrementAndGet()
      {
          return this.value++;
      }
      
      public int decrementAndGet()
      {
          return this.value--;
      }
      

      }

      CounterClient

      public class CounterClient implements Runnable
      {
      //shared data
      private Counting counter;

      public CounterClient(Counting counter)
      {
          this.counter = counter;
      }
      
      public void run()
      {
          while(true)
          {
              System.out.println("Incrementing from " + Thread.currentThread().getName() );                
              System.out.println("Counter value in " + Thread.currentThread().getName() + " = " + counter.incrementAndGet());                
              
              try
              {
                  Thread.sleep(2000L);
              } catch (InterruptedException ex)
              {
                  Logger.getLogger(CounterClient.class.getName()).log(Level.SEVERE, null, ex);
              }
          }
      }
      

      }

      TestCounter

      public class TestCounter
      {
      public static void main(String args[])
      {
      Counter counter = new Counter();
      SafeCounter safeCounter = new SafeCounter();

          Executor exec = Executors.newCachedThreadPool();
          
          exec.execute(new CounterClient(counter));
          exec.execute(new CounterClient(counter));        
          /\*
          exec.execute(new CounterClient(safeCounter));
          exec.execute(new CounterClient(safeCounter));
           \*/
           
      }
      

      }

      I did a test run for this code and one of the outputs was this:

      Incrementing from pool-1-thread-1
      Incrementing from pool-1-thread-2
      Counter value in pool-1-thread-1 = 0
      Counter value in pool-1-thread-2 = 1
      Incrementing from pool-1-thread-2
      Incrementing from pool-1-thread-1
      Counter value in pool-1-thread-2 = 2
      Counter value in pool-1-thread-1 = 3
      Incrementing from pool-1-thread-2
      Incrementing from pool-1-thread-1
      Counter value in pool-1-thread-1 = 4
      Counter value in pool-1-thread-2 = 5
      Incrementing from pool-1-thread-2
      Incrementing from pool-1-thread-1
      Counter value in pool-1-thread-1 = 6
      Counter value in pool-1-thread-2 = 7
      Incrementing from pool-1-thread-1
      Counter value in pool-1-thread-1 = 8
      Incrementing from pool-1-thread-2
      Counter value in pool-1-thread-2 = 9
      Incrementing from pool-1-thread

      N Offline
      N Offline
      Nagy Vilmos
      wrote on last edited by
      #2

      The code you have will return the value then increment, or decrement. To perform the change before hand try:

      return ++this.value;

      It is not really thread safe, but it is such a trivial example that you won't see a problem.


      Panic, Chaos, Destruction. My work here is done. Drink. Get drunk. Fall over - P O'H OK, I will win to day or my name isn't Ethel Crudacre! - DD Ethel Crudacre I cannot live by bread alone. Bacon and ketchup are needed as well. - Trollslayer Have a bit more patience with newbies. Of course some of them act dumb - they're often *students*, for heaven's sake - Terry Pratchett

      1 Reply Last reply
      0
      Reply
      • Reply as topic
      Log in to reply
      • Oldest to Newest
      • Newest to Oldest
      • Most Votes


      • Login

      • Don't have an account? Register

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • World
      • Users
      • Groups