简体   繁体   中英

Java Multi threading semaphore

The counter variable does not accurately reflect how many times increment method is invoked. Why not, and how can it be fixed? (You do not have to write code, just use English.)

Original:

import java.util.*;
import java.lang.*;
import java.io.*;


class Foopadoop
{
public static int counter = 0;
public static void main(String[] args) throws Exception {
    Runnable r = new Runnable() {
        public void run() {
            while(true){
                counter++;
            }
        }
    };
    Thread t1 = new Thread(r);
    Thread t2 = new Thread(r);
    t1.start();
    t2.start();
}
}

Mine, I added a semaphore but I'm not sure if I'm doing it right or am I suppose to use a lock.

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.concurrent.Semaphore;

class Foopadoop
{
public static int counter = 0;
Semaphore lock = new Semaphore(0);
public static void main(String[] args) throws Exception {
    Runnable r = new Runnable() {
        try{public void run() {
            while(true){
                counter++;
                lock.acquire();
            }
        }
       }finally{
         lock.release();
        }
    };
    Thread t1 = new Thread(r);
    Thread t2 = new Thread(r);
    t1.start();
    t2.start();
}
}

That's not how you use a Semaphore .

You acquire it before you access the shared resource, and release it after:

while (true) {
  try {
    lock.acquire();
    counter++;
  } finally {
    lock.release();
  }
}

Since you acquire first, you will also need at least 1 permit, otherwise there is nothing to acquire :

static Semaphore lock = new Semaphore(1);

A synchronized block is easier than a Semaphore :

while (true) {
  synchronized (Foopadoop.class) {
    counter++;
  }
}

or an AtomicInteger:

static AtomicInteger counter = new AtomicInteger();

// ...

while (true) {
  counter.getAndIncrement();
}

Also you can add Thread.sleep(ms) inside the while loop, so that it will pause the current thread for some time, & start executing other threads. Otherwise the current thread might run in a selfish manner (selfish thread).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM