Sudip
Sudip

Reputation: 92

How to increase volatile int in java using multiple thread?

I have a volatile int variable with value 0 that I want to increase up to 100 using 5 thread. I am trying to generate result from 0 to 100 with no duplicate. Can anyone please help me to resolve this.

I try this approach. Is it proper?

public class Producer implements Runnable {
    VolatileIncrement vo = null;
    String str = null;
    Producer(VolatileIncrement vo, String str){
        this.vo = vo;
        this.str = str;
    }

    @Override
    public void run() {
        while(vo.i < 100){
            System.out.println(str+vo.increaseI());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }   
    }
}

public class VolatileIncrement {    
    volatile Integer i = 0;
    public synchronized int increaseI() {
            i++;
            return i;
        }
    }
}

public class ProducerMain {
    public static void main(String[] args) {
        VolatileIncrement vo = new VolatileIncrement();
        Producer p1 = new Producer(vo,"I am thread 1 - ");
        new Thread(p1).start();
        Producer p2 = new Producer(vo,"I am thread 2 - ");
        new Thread(p2).start();
        Producer p3 = new Producer(vo,"I am thread 3 - ");
        new Thread(p3).start();
        Producer p4 = new Producer(vo,"I am thread 4 - ");
        new Thread(p4).start();
        Producer p5 = new Producer(vo,"I am thread 5 - ");
        new Thread(p5).start();
    }
}

Upvotes: 1

Views: 1484

Answers (3)

AMing
AMing

Reputation: 5747

You can use atomic1 classes for the update an integer by multi-threads

AtomicLong counter = new AtomicLong(0);
counter.getAndIncrement();

It is lock-free and thread-safe on single variable.

Upvotes: 1

user2023577
user2023577

Reputation: 2101

a) there is no reason to use volatile if all accesses to that variable is within a synchronized block. Synchronized has a larger scope than volatile for syncing memory between threads.

b) you cannot make a simple i++ atomic; you need synchronization, or reentrant locks, or the said AtomicInteger.

Upvotes: 0

Vaibhav G
Vaibhav G

Reputation: 647

int counter=0;
public static synchronized void increase()
{
     counter++;
}

Call this method.. Since its declared synchronized only one thread will act at a time (i.e. increment at a time).

Upvotes: 0

Related Questions