Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke two threads at same time?

I am trying to write Thread Interference Example.

Below is my code:

class Counter {
    private int c = 0;

    public void increment() {
        c++;
    }

    public void decrement() {
        c--;
    }

    public int value() {
        return c;
    }    
}

Suppose Thread A invokes increment at about the same time Thread B invokes decrement. How to implement this one.


2 Answers

There is not guarantee how they will run it depends on OS scheduler. There is nothing better than this

Thread a = new ThreadA();
Thread b = new ThreadB();
a.start();
b.start();
like image 73
Evgeniy Dorofeev Avatar answered Aug 13 '26 15:08

Evgeniy Dorofeev


To get two threads to start executing at the same time you can use a latch. (Which is to say, two threads that become available for execution as close together as possible.) Still for a single increment/decrement each it will probably take many runs to observe an interference. For a repeatable experiment you probably want to call increment/decrement several times in parallel and observe the final value of c.

final Counter counter = new Counter()
final CountDownLatch latch = new CountDownLatch(1);
Thread thread1 = new Thread(new Runnable() {
public void run() {
  latch.await();
  for (int i = 0; i < 100; i++) {
    counter.increment();
  }
}}).start():
Thread thread2 = new Thread(new Runnable() {
public void run() {
  latch.await();
  for (int i = 0; i < 100; i++) {
    counter.decrement();
  }
}}).start():
Thread.sleep(10);//give thread 2 a timeslice to hit the await
latch.countDown();
System.out.println(counter.value()); //non-zero value indicates interference
like image 30
Affe Avatar answered Aug 13 '26 16:08

Affe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!