Incrementing variable multi-threading - java

Suppose I have 10 threads that are incrementing a variable by 1. Suppose Thread-1 increments a variable first, and then Thread-2 and Thread-3 and consecutively. after all the 10 Threads have incremented the variable. I need to decrement the same variable in a manner.
Decrementing, if Thread-1 incremented the variable first of all, then it should decrement at last.
We need to do this without setting thread priority.

you can use a lot of ways, here's one for example:
public class Main {
public static void main(String[] args) throws Exception {
for(int i=0;i<10;i++){
final int _i=i;
Thread t = new Thread(new T(_i));
t.start();
}
}
public static class T implements Runnable{
int threadNumber;
public T(int threadNumber) {
this.threadNumber=threadNumber;
}
#Override
public void run() {
increase(this);
}
}
static Thread[] threads = new Thread[10];
static int number =0;
static Object generalLock=new Object();
public static void increase(T t){
int myNumber=0;
synchronized (generalLock){
myNumber=number;
System.out.println("i am "+number+" incrementing, my real number "+t.threadNumber);
threads[number]=Thread.currentThread();
number++;
}
while (threads[9]==null){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int i=9;i>myNumber;i--){
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (generalLock){
System.out.println("i am "+number+" decrementing, my real number "+t.threadNumber);
number--;
}
}
}
output example:
i am 0 incrementing, my real number 1
i am 1 incrementing, my real number 8
i am 2 incrementing, my real number 9
i am 3 incrementing, my real number 7
i am 4 incrementing, my real number 6
i am 5 incrementing, my real number 5
i am 6 incrementing, my real number 0
i am 7 incrementing, my real number 4
i am 8 incrementing, my real number 3
i am 9 incrementing, my real number 2
i am 9 decrementing, my real number 2
i am 8 decrementing, my real number 3
i am 7 decrementing, my real number 4
i am 6 decrementing, my real number 0
i am 5 decrementing, my real number 5
i am 4 decrementing, my real number 6
i am 3 decrementing, my real number 7
i am 2 decrementing, my real number 9
i am 1 decrementing, my real number 8
i am 0 decrementing, my real number 1
Note: you can use simple Runnable, I create T class to show the thread number in order to print it while incrementing/decrementing

This seems to work. Essentially I create the 10 threads and specially identify one of them using an enum. They all try to increment the shared integer, identifying themselves. The incrementer detects the first increment by noticing the transition to 1 and if it's a Special thread it returns true .
There's also a CountDownLatch used to synchronise all of the threads to ensure there is at least a chance of the two alternatives. I get about 8600 out of the 10000 test runs where the Special got there first. This value will vary depending on many variables.
enum Who {
Special, Normal;
}
class PriorityIncrementer {
final AtomicInteger i = new AtomicInteger(0);
boolean inc(Who who) {
return i.incrementAndGet() == 1 && who == Who.Special;
}
public void dec() {
i.decrementAndGet();
}
}
class TestRunnable implements Runnable {
final Who me;
final PriorityIncrementer incrementer;
final CountDownLatch latch;
public TestRunnable(PriorityIncrementer incrementer, CountDownLatch latch, Who me) {
this.incrementer = incrementer;
this.latch = latch;
this.me = me;
}
#Override
public void run() {
// Wait for all others to get here.
latch.countDown();
try {
// Wait here until everyone os waiting here.
latch.await();
// Do it.
if(incrementer.inc(me)) {
// I was first and special, decrement after.
incrementer.dec();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private boolean test(int count) throws InterruptedException {
Thread[] threads = new Thread[count];
// The shared incrementer.
PriorityIncrementer incrementer = new PriorityIncrementer();
// Arrange for all of them to synchronise.
CountDownLatch latch = new CountDownLatch(threads.length+1);
// One special.
threads[0] = new Thread(new TestRunnable(incrementer, latch, Who.Special));
// The rest are normal.
for(int i = 1; i < threads.length; i++) {
threads[i] = new Thread(new TestRunnable(incrementer, latch, Who.Normal));
}
// Start them up.
for (Thread thread : threads) {
thread.start();
}
// Wait a moment.
Thread.sleep(1);
// Start them all going.
latch.countDown();
// Wait for them to finish.
for (Thread thread : threads) {
thread.join();
}
// Who won?
return incrementer.i.get() < count;
}
public void test() throws InterruptedException {
final int tests = 10000;
int specialWasFirstCount = 0;
for (int i = 0; i < tests; i++) {
if(test(10)) {
specialWasFirstCount += 1;
}
}
System.out.println("Specials: "+specialWasFirstCount+"/"+tests);
}

Related

ReentrantLock threads terminating randomly

I have been working on a school assignment which is about multithreading in Java. One of the tasks that I am stuck on is that we need to create multiple threads in different groups, and once there are 4 threads in each group, only then they can be released to work in unison, otherwise they have to be put on hold/waiting. For example:
Thread a,b,c joins group 7, they are all put on hold/waiting.
Thread d joins group 7, all four threads (a,b,c,d) are signaled to be terminated.
Thread e,f,g,h,i joins group 8, in this case e,f,g,h will be signalled to be terminated while thread i is put on waiting.
Thread j joins group 7, it is put on for waiting.
That is the general task which I'm done with. The task I am working on requires us to release the INITIAL first 4 threads of a group, and the rest should wait until 4 of the previous threads have called finished().
For example, 3 threads join group 65, they are put on wait. Another thread joins group 65 and all 4 threads are released together. Now 4 threads are working (terminated). Now thread e,f,g,h,i,j,k,l join group 65. All of them are put to wait until e,f,g,h have called finished() method.
Here is what I have done so far:
ExtrinsicSync.java:
import java.util.HashMap;
import java.util.concurrent.locks.ReentrantLock;
public class ExtrinsicSync {
private HashMap<Integer, ConditionWrapper> groupThreadCount;
private ReentrantLock monitor;
private int count = 0;
ExtrinsicSync() {
groupThreadCount = new HashMap<>();
monitor = new ReentrantLock();
}
#Override
public void waitForThreadsInGroup(int groupId) {
monitor.lock();
if (!groupThreadCount.containsKey(groupId))
groupThreadCount.put(groupId, new ConditionWrapper(monitor.newCondition()));
ConditionWrapper condWrapper = groupThreadCount.get(groupId);
condWrapper.setValue(condWrapper.getValue() + 1);
if(condWrapper.getValue() == 4 && condWrapper.getInitialStatus())
{
condWrapper.getCondition().signalAll();
condWrapper.setInitialStatus(false);
System.out.println("Terminating group: " + groupId + "FROM INITIAL STATE: " + ++count);
} else {
System.out.println("Putting thread from group: " + groupId + " on wait: " + ++waitcount);
try { condWrapper.getCondition().await(); }
catch (InterruptedException e) { e.printStackTrace(); }
}
monitor.unlock();
}
#Override
public void finished(int groupId) {
monitor.lock();
ConditionWrapper condWrapper = groupThreadCount.get(groupId);
if(!condWrapper.getInitialStatus())
{
condWrapper.setFinishedCount(condWrapper.getFinishedCount() + 1);
System.out.println("Group: " + groupId + "FINISHED COUNT: " + condWrapper.getFinishedCount());
if(condWrapper.getFinishedCount() == 4)
{
condWrapper.setFinishedCount(0);
condWrapper.getCondition().signalAll();
System.out.println("Terminating threads for group: " + groupId + ": " + ++count);
}
}
monitor.unlock();
}
ExtrinsicSyncTest.java:
import org.junit.Test;
import java.util.EnumMap;
class TestTask1 implements Runnable{
final int group;
final ExtrinsicSync s1;
TestTask1(int group, ExtrinsicSync s1)
{
this.group = group;
this.s1 = s1;
}
public void run() { s1.waitForThreadsInGroup(group); s1.finished(group); }
}
public class ExtrinsicSyncTest {
#Test
public void testPhaseThreethreads() {
int nThreads = 22;
Thread t[] = new Thread[nThreads];
final ExtrinsicSync s1 = new ExtrinsicSync();
for(int i = 0; i < nThreads/2; i++)
(t[i] = new Thread(new TestTask1(66, s1))).start();
for(int i = nThreads/2; i < nThreads; i++)
(t[i] = new Thread(new TestTask1(70, s1))).start();
for (Thread ti : t)
{
try { ti.join(100); }
catch (Exception e) { System.out.println(e); }
}
EnumMap<Thread.State, Integer> threadsInThisState = new EnumMap<>(Thread.State.class);
for (Thread.State s : Thread.State.values())
threadsInThisState.put(s, 0);
for (Thread ti : t)
{
Thread.State state = ti.getState();
int n = threadsInThisState.get(state);
threadsInThisState.put(state, n + 1);
}
System.out.println("threadsInThisState: " + threadsInThisState.toString() );
}
}
ConditionWrapper.java:
import java.util.concurrent.locks.Condition;
public class ConditionWrapper {
private Condition cond;
private Integer value;
private Integer finishedCount;
private boolean initialThreads;
public ConditionWrapper(Condition condition)
{
this.cond = condition;
this.value = 0;
this.finishedCount = 0;
this.initialThreads = true;
}
// Returns the condition object of current request
public Condition getCondition()
{
return this.cond;
}
// Gets the current counter of threads waiting in this queue.
public Integer getValue()
{
return this.value;
}
// Sets the given value. Used for resetting the counter.
public void setValue(int value) { this.value = value; }
// Sets the counter to help keep track of threads which called finished() method
public void setFinishedCount(int count) { this.finishedCount = count; }
// Gets the finished count.
public Integer getFinishedCount() { return this.finishedCount; }
// This flag is to identify initial threads of a group
public boolean getInitialStatus() { return initialThreads; }
public void setInitialStatus(boolean val) { this.initialThreads = val; }
}
The problem I am having is that I am able to release the first four threads of every group, but somehow, somewhere 2 threads are being terminated randomly and I cannot figure out what is going on. For example, with 22 threads test case above divided into two groups, only 8 threads should be terminated while the rest of them wait.
But here 10 threads are being terminated instead. I do not understand what is going on. I have stripped the code down to bare minimum as best as I could.
The problem is that for the not initial threads (getInitialStatus==false) you do not signal the other threads but you still terminate them when you reached four of them. So this is what happens:
first three threads increase the count and wait
the fourth thread reaches count == 4 and sets initial = false and signals all the other threads and sets the count to zero
the next three threads increase the count by one
the 8 threads reaches count == 4 and gets terminated. Since getInitialStatus==false this thread does not notify the other threads.
so 4*2 threads + 2 threads get terminated. Exactly the count you have seen in your tests.
Here is a potential way to implement this:
use a flag canExecute in each thread or task
use a method calculateState to calculate the current state and set the flag to true if a thread is allowed to execute.
store all threads which are waiting in a list or something similar
So your task would look like this:
Task
boolean canExeute
The method waitForThreadsInGroup then lookslike this:
waitForThreadsInGroup
monitor.lock();
add task to list
calculateTaskState
condition.notifyAll
while( ! task.canExcecute )
{
condition.await.
}
monitor.unlock();
The finish method looks similar:
finish
monitor.lock();
decrement finish count
calculateTaskState
condition.notifyAll
monitor.unlock();
And calculateTaskState
calculateTaskState
if( finishCount == 0)
{
if( taskList.size >= 4 )
{
set 4 tasks in this list to can execute and remove them from the list
}
}
So the trick is to separate the logic into three steps:
the action, for example reducing the finish count
the calculation of the new state. And deciding for each thread if it is allowed to execute
And the waiting of the threads. Each thread needs to wait on its own flag

Can FairSync guarantee the order of execution?

My first question, Thank for your help!
I'm trying to print odd and even numbers 1~100 alternatively using two threads.
Expected results:
pool-1-thread-1=> 1
pool-1-thread-2=> 2
pool-1-thread-1=> 3
pool-1-thread-2=> 4
......
pool-1-thread-1=> 99
pool-1-thread-2=> 100
I think i can use FairSync, but it can only guarantee that most of the print is correct. like this:
pool-1-thread-1=> 55
pool-1-thread-2=> 56
pool-1-thread-1=> 57
pool-1-thread-2=> 58
pool-1-thread-2=> 59 //※error print※
pool-1-thread-1=> 60
pool-1-thread-2=> 61
pool-1-thread-1=> 62
I don't know why is the order lost in very few cases?
You can criticize my code and my English.
Here is my code:
private static final int COUNT = 100;
private static final int THREAD_COUNT = 2;
private static int curr = 1;
static ReentrantLock lock = new ReentrantLock(true);
static ExecutorService executorService = Executors.newCachedThreadPool();
public static void main(String[] args) {
Runnable task = () -> {
for (; ; ) {
try {
lock.lock();
if (curr <= COUNT) {
System.out.println(Thread.currentThread().getName() + "=> " + curr++);
} else {
System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
};
for (int i = 0; i < THREAD_COUNT; i++) {
executorService.execute(task);
}
}
No dear your implementation is not correct. Which thread get's the opportunity to RUN is decided by the OS. Thread 1 & 2 will execute one after another cannot be guaranteed.
You can fix your code by checking the previous value of the variable curr and if the value is not what this thread expects don't increment and print.
for eg :
if(curr.threadName.equals("Thread 2") && (curr%2 !=0))
{
// Print
// Increment
}
You cant use single lock to achieve this. Even ReentrantLock gives fairness but it cant control thread schedule.
We can achieve throw inter thread communication like Semaphore. Semaphore controls the thread execution.
We create two threads, an odd thread, and an even thread. The odd thread would print the odd numbers starting from 1, and the even thread will print the even numbers starting from 2.
Create two semaphores, semOdd and semEven which will have 1 and 0 permits to start with. This will ensure that odd number gets printed first.
class SharedPrinter {
private Semaphore semEven = new Semaphore(0);
private Semaphore semOdd = new Semaphore(1);
void printEvenNum(int num) {
try {
semEven.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(Thread.currentThread().getName() + num);
semOdd.release();
}
void printOddNum(int num) {
try {
semOdd.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(Thread.currentThread().getName() + num);
semEven.release();
}
}
class Even implements Runnable {
private SharedPrinter sp;
private int max;
// standard constructor
#Override
public void run() {
for (int i = 2; i <= max; i = i + 2) {
sp.printEvenNum(i);
}
}
}
class Odd implements Runnable {
private SharedPrinter sp;
private int max;
// standard constructors
#Override
public void run() {
for (int i = 1; i <= max; i = i + 2) {
sp.printOddNum(i);
}
}
}
public static void main(String[] args) {
SharedPrinter sp = new SharedPrinter();
Thread odd = new Thread(new Odd(sp, 10),"Odd");
Thread even = new Thread(new Even(sp, 10),"Even");
odd.start();
even.start();
}
Refer : here

Multithreaded program - Threads cutting each other off

I am just testing out some threads, trying to figure out how to use them. My question is, how can I get my current scenario to work how I want it?
I want to have this program print out 1 - 100. I have two methods; oddNumbers and evenNumbers
oddNumbers:
public static void oddNumbers() {
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 1) {
System.out.println(i);
}
}
}
}).start();
}
evenNumbers:
public static void evenNumbers() {
new Thread(new Runnable() {
public void run() {
for (int q = 0; q < 100; q++) {
if (q % 2 == 0) {
System.out.println(q);
}
}
}
}).start();
}
main method
public static void main(String[] args) {
evenNumbers();
oddNumbers();
}
So, from what I understand, the methods oddNumbers and evenNumbers are running on different threads. So if they are, then why isn't my output 1-100?
Here's the output I get:
0
2
4
6
.
.
.
50
1
3
5
.
.
.
99
52
54
56
.
.
.
100
About half way through the evenNumbers loop, the oddNumbers loop cuts it off. Why does this happen, and how do I set it up so that it'll print 1-100?
Thanks in advance!
Because you did not tell threads to wait remaining participants.
It is hard to tell if next thread continues its work just after started or how long it will take to start. It could be several cpu cycles or 2 seconds.
You want exact instruction timing for realtime critical app? Start fpga programming.
For this java pc program, you could have used cyclic barrier just to let them do steps together without any starting priority importance.
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class Demo {
public static CyclicBarrier barrier = new CyclicBarrier(2);
public static void oddNumbers() {
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 100; i++) {
try {
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (i % 2 == 1) {
System.out.println(i);
}
}
}
}).start();
}
public static void evenNumbers() {
new Thread(new Runnable() {
public void run() {
for (int q = 0; q < 100; q++) {
try {
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (q % 2 == 0) {
System.out.println(q);
}
}
}
}).start();
}
public static void main(String[] args) {
evenNumbers();
oddNumbers();
}
}
barrier instance is created here with room for 2 threads so every 2 await action resets it and threads can wait on it again on next iteration.
Still, it has probability to output:
1
0
3
2
5
4
...
instead of
0
1
2
3
it could be solved using a third action to combine 2 threads results before printing to console.
The hardness here is you ask for serial action in a multithreaded environment.
I understand you don't want them to be alternated, just understand why each is executed for so long.
That decision is taken by the scheduler of the operating system. It decides when to switch to another thread. The thing with your example is that your threads are so small, they are executed so quickly.
The scheduler gives the power to be executed to a thread for some time, the problem is, that time is enough to display so many numbers of your loop, so they are not switched many times.
You would get better results if you had it running longer, use much bigger numbers. Or, you can also make the loops take longer before printing, add some calculus that takes time, so that it doesn't print that many numbers in a row.

I can't understand how examples with synchronized work

I just started learning "multithreading" in JAVA and it seams I don't understand how keyword "synchronized" works.
I had four examples and they're very alike (in my opinion), and I don't understand why I get every time different results.
public class BufferThread1 {
static int counter = 0;
static StringBuffer s = new StringBuffer();
public static void main(String args[]) throws InterruptedException {
new Thread() {
public void run() {
synchronized (s) {
while (BufferThread1.counter++ < 3) {
s.append("A");
System.out.print("> " + counter + " ");
System.out.println(s);
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(BufferThread1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}.start();
Thread.sleep(100);
while (BufferThread1.counter++ < 6) {
System.out.print("< " + counter + " ");
s.append("B");
System.out.println(s);
}
}
}
Result:
run:
> 1 A
< 2 > 3 AA
AAB
< 5 AABB
< 6 AABBB
public class BufferThread2 {
static int counter = 0;
static StringBuilder s = new StringBuilder();
public static void main(String args[]) throws InterruptedException {
new Thread() {
public void run() {
synchronized (s) {
while (BufferThread2.counter++ < 3) {
s.append("A");
System.out.print("> " + counter + " ");
System.out.println(s);
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(BufferThread2.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}.start();
Thread.sleep(100);
while (BufferThread2.counter++ < 6) {
System.out.print("< " + counter + " ");
s.append("B");
System.out.println(s);
}
}
}
Result:
run:
> 1 A
< 2 AB
< 3 ABB
< 4 ABBB
< 5 ABBBB
< 6 ABBBBB
public class BufferThread3 {
static int counter = 0;
static StringBuffer s = new StringBuffer();
public static void main(String args[]) throws InterruptedException {
new Thread() {
public void run() {
synchronized (s) {
while (BufferThread3.counter++ < 3) {
s.append("A");
System.out.print("> " + counter + " ");
System.out.println(s);
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(BufferThread3.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}.start();
Thread.sleep(100);
synchronized (s) {
while (BufferThread3.counter++ < 6) {
System.out.print("< " + counter + " ");
s.append("B");
System.out.println(s);
}
}}
}
Result:
run:
> 1 A
> 2 AA
> 3 AAA
< 5 AAAB
< 6 AAABB
Of course, I skipped
import java.util.logging.Level;
import java.util.logging.Logger;
I just don't realise how these examples work and synchronized here !
I do hope that someone help me.
Your < and > label which thread is running here.
> 1 A
Your background thread is running only and prints this line as expected.
< 2
The main thread prints the counter 2 but cannot acquire the lock on s so it blocks.
> 3 AA
The background thread increments the counter again and prints 3 and a second A. On the next iteration it exits and counter == 4 As the thread exits, it releases the lock.
AAB
The main thread can now acquire the lock and append("B")
< 5 AABB
The main thread increments the counter to 5 and adds another B
StringBuffer is a pet hate of mine which was replaced more thna ten years ago by StringBuidler. It is almost impossible to implement a useful thread safe class using it and when people have tried, it has meant the class wasn't really thread safe. Note: SimpleDateFormat uses StringBuffer and it is not thread safe.
Let's try a simpler example that gets at what synchronized does without such an overly complicated class.
Consider the following Runnable task:
public class Task implements Runnable {
private final int id;
public Task(int id) {
this.id = id;
}
public void run() {
for(int i = 0; i < 5; i++) {
System.out.println("Task " + id + " prints " + i);
}
}
}
Then let's try running it with this main method:
public static void main(String[] args) {
Thread t1 = new Thread(new Task(1));
Thread t2 = new Thread(new Task(2));
t1.start();
t2.start();
}
The output could look something like this:
Task 1 prints 0
Task 1 prints 1
Task 1 prints 2
Task 1 prints 3
Task 1 prints 4
Task 2 prints 0
Task 2 prints 1
Task 2 prints 2
Task 2 prints 3
Task 2 prints 4
But it could also look like this:
Task 1 prints 0
Task 2 prints 0
Task 2 prints 1
Task 1 prints 1
Task 1 prints 2
Task 1 prints 3
Task 1 prints 4
Task 2 prints 2
Task 2 prints 3
Task 2 prints 4
Task 2 prints 4
The truth is, you have no guarantees about the order in which the two Tasks execute commands (with respect to each other. You still do know that each task will print 0...4 in order). The fact that t1.start() comes before t2.start() means nothing.
The synchronized command allows for some control over which thread executes when. Essentially, the command synchronized(obj) {....} means that at most one thread is allowed to execute the commands in the block (within the {...}) at a time. This is know as mutual exclusion.
A nice way to think about it is as a locked room with a single key hanging outside on the wall. In order to get into the room, you have to take the key off the wall, unlock the door, go into the room, and lock it from the inside. Once you are done doing whatever you are doing in the room, you unlock the door from the inside, go outside, lock the door from the outside, and hang the key up. It is clear that while you are in the room no one else can join you, as the door is locked and you currently hold the only key to get in.
To illustrate, consider the following improved task class:
public class SynchronizedTask implements Runnable {
private final Object lock;
private final int id;
public Task(int id, Object lock) {
this.id = id;
this.lock = lock;
}
public void run() {
synchronized(lock) {
for(int i = 0; i < 5; i++) {
System.out.println("Task " + id + " prints " + i);
}
}
}
}
And run it with the following modified main method:
public static void main(String[] args) {
Object lock = new Object();
Thread t1 = new Thread(new Task(1, lock));
Thread t2 = new Thread(new Task(2, lock));
t1.start();
t2.start();
}
We still don't know whether t1 or t2 will enter the synchronized block first. However, once has entered, the other must wait for it to finish. Thus, there are exactly two possible outputs of this code. Either t1 gets in first:
Task 1 prints 0
Task 1 prints 1
Task 1 prints 2
Task 1 prints 3
Task 1 prints 4
Task 2 prints 0
Task 2 prints 1
Task 2 prints 2
Task 2 prints 3
Task 2 prints 4
Or t2 gets in first:
Task 2 prints 0
Task 2 prints 1
Task 2 prints 2
Task 2 prints 3
Task 2 prints 4
Task 1 prints 0
Task 1 prints 1
Task 1 prints 2
Task 1 prints 3
Task 1 prints 4
It is important to note that this behavior only worked as desired because we used the same lock object for both Tasks. If we had run the following code instead:
public static void main(String[] args) {
Thread t1 = new Thread(new Task(1, new Object()));
Thread t2 = new Thread(new Task(2, new Object()));
t1.start();
t2.start();
}
We would have identical behavior to the original un-synchronized code. This is because we now have a room with two (or really, infinite if we replicate our thread initialization) keys hanging outside. Thus while t1 is inside the synchronized block, t2 can just use its own key to get in, defeating the whole purpose.
First example shown by Mr. Lawrey.
In the second example the "Background" thread only gets to do one print of and since StringBuilder is used this time instead of StringBuffer the main thread will not block while trying to print "s", hence only 1 A.
In the third example the main thread is blocked until the background thread terminates because you start the background thread before the main thread's loop. Thus the background thread will get 3 loops done and hence the 3 A's.
Though I suspect these are artificial examples for learning purposes it should still be noted that sleeping inside a synchronized block is NOT a good idea as this will not release the lock.

Print 1 to 100 using 10 threads in java

I'm new to muti-threading and I got a question to print 1 to 100 using 10 threads in Java with below constrain.
Thread t1 should print:
1, 11, 21, 31, ... 91
t2 should print:
2, 12, 22, 32, ... 92
likewise
t10 should print:
10, 20, 30, ... 100
The final output should be
1 2 3 .. 100
I have tried it, but it is throwing the following exception in all 10 threads:
java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:485)
at thread.run(MyThread.java:58)
at java.lang.Thread.run(Unknown Source)
Please let me know how I can solve this problem.
public class MyThread {
/**
* #param args
*/
public static void main(String[] args) {
thread.setSequence();
for(int i = 1; i <= 10; i++) {
Thread t = new Thread(new thread(i));
t.setName(i + "");
t.start();
}
}
}
class thread implements Runnable {
private static HashMap< String, String> sequence = new HashMap<String, String>();
public static final Object lock = new Object();
public static String turn = "1";
private int startValue = 0;
private AtomicInteger counter = new AtomicInteger(1);
public thread(int startValue){
this.startValue = startValue;
}
#Override
public void run() {
while (!counter.equals(10)){
synchronized (lock) {
if(Thread.currentThread().getName().equals(turn)){
System.out.print(startValue + " ");
startValue += 10;
counter.incrementAndGet();
turn = getNextTurn(turn);
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else{
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
}
}
}
public static void setSequence(){
for (int i = 1; i <= 10; i++)
if (i == 10)
sequence.put(i + "", 1 + "");
else
sequence.put(i + "", (i + 1) + "");
}
public static String getNextTurn(String currentTurn){
return sequence.get(currentTurn);
}
}
The simplest way would be to have a volatile variable from which each thread reads in and update according to its turn, otherwise it just waits until his turn. When counter is equals to 100 you stop all threads to run by breaking the outer loop.
class MyRunnable implements Runnable {
private static final int LIMIT = 20;
private static volatile int counter = 0;
private int id;
public MyRunnable(int id) {
this.id = id;
}
#Override
public void run() {
outer:
while(counter < LIMIT) {
while (counter % NB_THREADS != id) {
if(counter == LIMIT) break outer;
}
System.out.println("Thread "+Thread.currentThread().getName()+ " printed " + counter);
counter += 1;
}
}
}
Given a LIMIT of 20 and 10 threads, it outputs:
Thread 0 printed 0
Thread 1 printed 1
Thread 2 printed 2
Thread 3 printed 3
Thread 4 printed 4
Thread 5 printed 5
Thread 6 printed 6
Thread 7 printed 7
Thread 8 printed 8
Thread 9 printed 9
Thread 0 printed 10
Thread 1 printed 11
Thread 2 printed 12
Thread 3 printed 13
Thread 4 printed 14
Thread 5 printed 15
Thread 6 printed 16
Thread 7 printed 17
Thread 8 printed 18
Thread 9 printed 19
Of course, this is a very bad usage of multithreading because each thread waits its turn to print and increment the counter.
Multithreading works well when threads can work independently of another for relatively long time's window, and then may occasionally meet up to compare or combine their results if needed.
For example in the fork-join model, each thread does its task independently then their results are merged to produce the final outcome, such as in a merge sort for example. But this assume that the task can be easily parallelizable into independant subtasks, which is not the case here because your final output should be consecutive numbers.
So here a simple loop would be largely more efficient, but I can understand it's for learning purposes.
Here is a solution for the problem.The current thread acquire the lock and we decide if the thread is eligible to execute (printing the number here). If so perform the operation and notify all threads that they can try now. Else wait till its notified by other threads.
public class MyThread extends Thread{
//define the Total No.Of Threads needed
public static final int TOTAL_THREADS = 10;
public final static Object obj = new Object();
int threadNo;
static volatile int counter = 1;
public MyThread(int threadNo){
this.threadNo= threadNo;
}
#Override
public void run(){
//in a synchronized block to acquire lock
synchronized (obj) {
while(counter<=100){
/*
* counter==threadNo => To print the initial numbers till TOTAL_THREADS
* counter%TOTAL_THREADS == threadNo => e.g 11%10 = 1 -> 1 will print this, 12%10 = 2 ..
* (counter%TOTAL_THREADS == 0) && (TOTAL_THREADS == threadNo) => 10%10 will be 0,
* and this must be printed by 10 th thread only, ie the highest thread.
*/
if(counter == threadNo || (counter%TOTAL_THREADS == threadNo) ||
((counter%TOTAL_THREADS == 0) && (TOTAL_THREADS == threadNo))){
//Display the output as desired
System.out.println(this.threadNo+" printing"+" "+counter++);
//notify
obj.notifyAll();
}else{
//current thread not eligible for printing the current counter value, so wait till its notified
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main (String args[]) {
/*
* Creating as many threads as needed.
*/
for(int i = 1; i<=TOTAL_THREADS;i++){
MyThread th = new MyThread(i);
th.start();
}
}
}
The output will be
1 printing 1,
2 printing 2,
3 printing 3,
4 printing 4,
5 printing 5,
6 printing 6,
7 printing 7,
8 printing 8,
9 printing 9,
10 printing 10,
1 printing 11,
2 printing 12,
3 printing 13,
4 printing 14,
...
7 printing 97,
8 printing 98,
9 printing 99,
10 printing 100
Hope this helps =) Took me an hour to do it.
package com.xxxx.simpleapp;
import java.util.ArrayList;
import java.util.List;
public class TenThreads {
public int currentTaskValue = 1;
public static void main(String[] args) {
TenThreads monitor = new TenThreads();
List<ModThread> list = new ArrayList();
for (int i = 0; i < 10; i++) {
ModThread modThread = new ModThread(i, monitor);
list.add(modThread);
}
for (ModThread a : list) {
a.start();
}
}
}
class ModThread extends Thread {
private int modValue;
private TenThreads monitor;
public ModThread(int modValue, TenThreads monitor) {
this.modValue = modValue;
this.monitor = monitor;
}
#Override
public void run() {
synchronized (monitor) {
try {
while (true) {
while (monitor.currentTaskValue % 10 != modValue) {
monitor.wait();
}
if (monitor.currentTaskValue == 101) {
break;
}
System.out.println(Thread.currentThread().getName() + " : "
+ monitor.currentTaskValue + " ,");
monitor.currentTaskValue = monitor.currentTaskValue + 1;
monitor.notifyAll();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
output
Thread-1 : 1 ,
Thread-2 : 2 ,
Thread-3 : 3 ,
Thread-4 : 4 ,
Thread-5 : 5 ,
Thread-6 : 6 ,
Thread-7 : 7 ,
Thread-8 : 8 ,
Thread-9 : 9 ,
......
.....
...
Thread-4 : 94 ,
Thread-5 : 95 ,
Thread-6 : 96 ,
Thread-7 : 97 ,
Thread-8 : 98 ,
Thread-9 : 99 ,
Thread-0 : 100 ,
Documentation are intentionally left out for you to figure it out, there are minor bugs too!
Error is thrown due to calling of wait not on proper object. wait() should be called on object on which lock is acquired, the one implied by synchronized keyword.
Well I do not have the code...but the perspective seems to be
that there are 100 tasks to be executed each of incrementing
a count by 1.
So there could be a ThreadPool of say 10 threads and these
threads are incrementing the shared count value...
Only point to consider is that the Thread pools worker threads
have to sequentially execute their tasks one after the other
and the thread sequence for the 10 have to be maintained...
One simple way to solve this is use below state in runnable class
private final int index;
private final AtomicInteger atomicInteger;
private final CyclicBarrier cyclicBarrier;
index - is responsible for conditional verification i.e., which number this thread should print.
atomicInteger - shared across all threads for current number.
Cyclic barrier - makes all threads to wait unit a every thread completes a cycle/iteration.
Code sample:
public class PrintSequence {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
final AtomicInteger atomicInteger = new AtomicInteger(1);
final CyclicBarrier cyclicBarrier = new CyclicBarrier(10, ()-> {
System.out.println("a cycle done");
});
IntStream.rangeClosed(0, 9)
.boxed()
.map(i -> new PrintSequenceTask(i, atomicInteger, cyclicBarrier))
.map(p -> executorService.submit(p))
.collect(Collectors.toList());
executorService.shutdown();
}
}
class PrintSequenceTask implements Runnable {
private final int index;
private final AtomicInteger atomicInteger;
private final CyclicBarrier cyclicBarrier;
PrintSequenceTask(int index, AtomicInteger atomicInteger, CyclicBarrier cyclicBarrier) {
this.index = index;
this.atomicInteger = atomicInteger;
this.cyclicBarrier = cyclicBarrier;
}
#Override
public void run(){
for(int i=1; i<10;i++){
while (((atomicInteger.get()-index-1)%10 != 0)){}
System.out.println(Thread.currentThread().getName()+" "+(atomicInteger.get()));
atomicInteger.getAndIncrement();
await();
}
}
public void await(){
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}
public class BigSequence {
public static void main(String[] args) {
BigPrintNum p = new BigPrintNum();
int max = 20;
int no_threads = 11;
for(int i=0;i<no_threads;i++){
boolean b[] = new boolean[no_threads];
b[i] = true;
Thread t = new Thread(new BigPrint(p, max, b,no_threads));
t.start();
}
}
}
class BigPrint implements Runnable {
int num=0;
BigPrintNum p;
int max;
int no_threads;
boolean b[];
public BigPrint(BigPrintNum p,int max,boolean b[],int no_threads){
this.p = p;
this.max = max;
this.b = b;
this.no_threads = no_threads;
}
#Override
public void run() {
int n = 0;
for(int i=0;i<no_threads;i++){
if(b[i] == true){
n = i;
num = i;
}
}
while(num<=max){
p.print(num, n, no_threads);
num += no_threads;
}
}
}
class BigPrintNum {
int turn = 0;
public synchronized void print(int n,int i,int no_threads){
while(this.turn != i){
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.println(i + "th seq = " + n);
this.turn = (i+1)%no_threads;
notifyAll();
}
}
Its a generic one, where we can use any number of threads and use any max value.
public class ThreadSequence
{
public static int totalThread;
public static void main(String[] args)
{
MyLock myLock = new MyLock();
totalThread = 10;
for(int i=1;i<=totalThread;i++)
{
MyThread myThread = new MyThread(i,myLock);
myThread.start();
}
}
}
class MyLock
{
public int counter = 0;
}
MyThread Class
class MyThread extends Thread{
public MyLock lock;
public int no;
public MyThread(int no,MyLock lock)
{
super("My Thread No "+no);
this.no = no;
this.lock = lock;
}
public void run()
{
synchronized (lock)
{
while(true)
{
while(lock.counter%ThreadSequence.totalThread !=(this.no-1))
{
try
{
if(lock.counter > 99)
{
break;
}
lock.wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
if(lock.counter > 99)
{
break;
}
System.out.println("Current Thread "+Thread.currentThread().currentThread()+" --- Current Count "+(lock.counter+1));
lock.counter = lock.counter +1 ;
lock.notifyAll();
}
}
}
}
print 1 to 100 number alternatively by each thread similar way you can print for 10 threads- m1 and m2 like
m1-1
m2-2
m3-3
m4-4
public class MultiThread extends Thread {
static volatile int num=0;
public static void main(String[] args) {
MultiThread m1= new MultiThread();
MultiThread m2= new MultiThread();
m1.setName("m1");
m1.setPriority(5);
m2.setName("m2");
m2.setPriority(5);
m1.start();
m2.start();
}
#Override
public void run() {
while(num<100) {
num +=1;
print();
}
}
private void print(){
synchronized(this) {
System.out.println(currentThread().getName()+" "+ num);
try {
currentThread().wait(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
The simple thing to do is to hold common resource for all of them.
Hold a List and every thread will insert into the list, in the end you can sort and print..
If you want them to do it on your order it won't be very effective because you won't need 10 threads to do it..
This way it will be faster and will use 10 threads to do some work, but when everyone finish you still need to do some work
public class PrintNumbersbyThreads implements Runnable {
private int i;
public PrintNumbersbyThreads(int i) {
this.i = i;
}
public static void main(String[] args) {
PrintNumbersbyThreads p = new PrintNumbersbyThreads(1);
PrintNumbersbyThreads p2 = new PrintNumbersbyThreads(2);
PrintNumbersbyThreads p3 = new PrintNumbersbyThreads(3);
Thread t1 = new Thread(p, "t1");
Thread t2 = new Thread(p2, "t2");
Thread t3 = new Thread(p3, "t3");
t1.start();
try {
t1.join();
t2.start();
t2.join();
t3.start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
public void run() {
System.out.println("\n" + Thread.currentThread().getName() + " prints ");
for (int j = 0; j < 10; j++) {
System.out.print(i + " ");
i = i + 10;
}
}
}
Written sample code 3 Threads and the output is
t1 prints:
1 11 21 31 41 51 61 71 81 91
t2 prints:
2 12 22 32 42 52 62 72 82 92
t3 prints:
3 13 23 33 43 53 63 73 83 93
Hope this is what you are Looking for?
I have written one generic code which will take the number till where you want to print and the number of threads to be used.
public class ThreadedPrinting {
private Object locks[];
private static class Printer extends Thread {
int curVal;
int endVal;
Object myLock;
Object nextLock;
int step;
public Printer(int startFrom, int endVal, int step, Object myLock, Object nextLock){
this.curVal = startFrom;
this.endVal = endVal;
this.step = step;
this.myLock = myLock;
this.nextLock = nextLock;
this.step = step;
}
#Override
public void run(){
synchronized(myLock) {
while (curVal <= endVal) {
try {
myLock.wait();
System.out.println(curVal);
curVal += step;
}
catch(InterruptedException e) {}
synchronized(nextLock) {
nextLock.notify();
}
}
}
synchronized(nextLock) {
nextLock.notify(); /// this ensures all worker threads exiting at the end
}
}
} // Printer
public ThreadedPrinting(int maxNum, int threads) {
locks = new Object[threads];
int i;
for(i = 0; i < threads; ++i) locks[i] = new Object();
for(i = 0; i < threads -1 ; ++i) {
Printer curPrinter = new Printer(i, maxNum, threads, locks[i], locks[i+1]);
curPrinter.start();
}
Printer lastPrinter = new Printer(i, maxNum, threads, locks[threads - 1], locks[0]);
lastPrinter.start();
}
public void start() {
synchronized (locks[0]) {
locks[0].notify();
}
}
public static void main(String[] args) {
ThreadedPrinting printer = new ThreadedPrinting(1000,7);
printer.start();
}
}
The same problem can be solved by usign Phaser as well but the order is not restrictive but will be in round-robin fashion. I have provided the solution for similar problem here.

Categories