Multithreading queue java - java

From the following code:
public class Main {
static String[] s = { "aaaaaaa", "bbbb", "ccc", "dd" };
public static void main(String[] args) {
Watek w = new Watek(0);
Watek w1 = new Watek(1);
Watek w2 = new Watek(2);
Watek w3 = new Watek(3);
w.start();
w1.start();
w2.start();
w3.start();
}
}
class Watek extends Thread {
int i;
public Watek(int i) {
this.i = i;
}
public void run() {
for (int j = 0; j < Main.s[i].length(); j++) {
System.out.print(Main.s[i].charAt(j) + " ");
}
}
}
I see on console
a a a a b b b b ect.
But i need:
a b c d a b c d...
I try to use wait();notify();, synchronized, but still i have a a a a or error
Can someone tell me how i need to do this ??

wait , synchronized and notifyAll will solve out your problem .
Instead of using single Thread class , I'll suggest you to use 4 diffrent Thread class 1 for each letter
Here is the working Example, It is Long as it is complete code
public class Main {
static String[] s = { "aaaaaaa", "bbbb", "ccc","ddd"};
static int status=1; // For Maintaning Order Of Processing of Threads
public static void main(String[] args) {
Main m=new Main(); // This Object's Lock is used by threads
Watek1 w1 = new Watek1(0,m);
Watek2 w2 = new Watek2(1,m);
Watek3 w3 = new Watek3(2,m);
Watek4 w4 = new Watek4(3,m);
w1.start();
w2.start();
w3.start();
w4.start();
}
}
class Watek1 extends Thread {
int i;
Main main;
public Watek1(int i,Main main) {
this.i = i;
this.main=main;
}
public void run() {
try
{
synchronized(main)
{
for (int j = 0; j < Main.s[i].length(); j++)
{
while(main.status!=1)
{
main.wait();
}
main.status=2;
System.out.print(Main.s[i].charAt(j) + " ");
main.notifyAll();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
class Watek2 extends Thread {
int i;
Main main;
public Watek2(int i,Main main) {
this.i = i;
this.main=main;
}
public void run() {
try
{
synchronized(main){
for (int j = 0; j < Main.s[i].length(); j++) {
while(main.status!=2)
{
main.wait();
}
System.out.print(Main.s[i].charAt(j) + " ");
main.status=3;
main.notifyAll();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
class Watek3 extends Thread {
int i;
Main main;
public Watek3(int i,Main main) {
this.i = i;
this.main=main;
}
public void run() {
try
{
synchronized(main){
for (int j = 0,counter=0; j < Main.s[i].length(); j++) {
while(main.status!=3)
{
main.wait();
}
System.out.print(Main.s[i].charAt(j) + " ");
main.status=4;
main.notifyAll();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
class Watek4 extends Thread {
int i;
Main main;
public Watek4(int i,Main main) {
this.i = i;
this.main=main;
}
public void run() {
try
{
synchronized(main){
for (int j = 0,counter=0; j < Main.s[i].length(); j++) {
while(main.status!=4)
{
main.wait();
}
System.out.print(Main.s[i].charAt(j) + " ");
main.status=1;
main.notifyAll();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Output
a b c d a b c d a b c d a b
The basic concept/logic behind this is that while 1 thread is executing others thread has to wait and once 1 thread complete it's processing it changes the status and also notifyAll threads inside waiting pool so that other thread able to execute .
And Status Counter is cyclic to print in order
1------------2
| |
| |
| |
| |
4------------3

Using #Neeraj code finally i have what i want.
If someone have the same problem i put my code:
import java.util.ArrayList;
public class Main {
static String[] s = { "aaaaa","bbbb", "ccc", "dd" ,"e"};
static ArrayList<Integer> lista = new ArrayList<Integer>();
public static void main(String[] args) {
// TODO Auto-generated method stub
Main m = new Main();
ArrayList<Thread> watki = new ArrayList<Thread>();
lista.add(0);
for(int i =0;i<s.length;i++){
watki.add(new Watek(i,m));
lista.add(i);
}
for(int i=0;i<watki.size();i++){
watki.get(i).start();
}
lista.remove(0);
}
}
class Watek extends Thread {
int i;
Main main;
public Watek(int i, Main main) {
this.i = i;
this.main= main;
}
public void run() {
synchronized (main) {
for (int j = 0; j < Main.s[i].length(); j++) {
while (main.lista.get(0) != i) {
try {
main.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(j<Main.s[i].length()-1)
main.lista.add(i);
main.lista.remove(0);
System.out.print(Main.s[i].charAt(j) + " ");
main.notifyAll();
}
}
}
}

Related

Print Floyd triangle using multithreading in java

I want to use two threads to print Floyd triangle(say one thread prints the number and the other prints the number in the line) as below.
and so forth until the max number which is 15 in this case.
I tried following but it keeps on printing numbers one on each line
public class MyThread extends Thread{
static volatile int lineNumber = 1;
public static void main(String... args) {
PrintFloyd print = new PrintFloyd();
Thread t1 = new Thread(new TaskHandler(print, 10), "T1");
Thread t2 = new Thread(new TaskHandler(print, 10), "T2");
t1.start();
t2.start();
}
}
class TaskHandler implements Runnable {
static volatile int i = 1;
static volatile int lineCount = 1;
static volatile int lineNumber = 1;
private int max;
private PrintFloyd print;
TaskHandler(PrintFloyd print2, int max) {
this.print = print2;
this.max = max;
}
#Override
public void run() {
System.out.println(">>>>" + Thread.currentThread().getName());
while(i < max){
if (Thread.currentThread().getName().equals("T1")){
print.printNumber(i);
} else {
print.breakLine();
}
}
}
}
class PrintFloyd {
boolean isBreakPoint = false;
public void printNumber(int i) {
synchronized(this){
while (isBreakPoint == false) {
try {
wait();
} catch (InterruptedException ex) {
}
System.out.print(i++ + " ");
isBreakPoint = false;
notifyAll();
}
}
}
public void breakLine(){
synchronized(this){
while (isBreakPoint == true) {
try {
wait();
} catch (InterruptedException ex) {
}
}
System.out.println();
isBreakPoint = true;
notifyAll();
}
}
}
The following code would help:
public class PrintPatternWith2Threads {
final static int MAX = 15;
final static String itemWriterName = "itemWriter";
final static String newLineWriterName = "newLineWriter";
public static void main(String[] args) {
Printer print = new Printer(MAX);
Thread itemWriter = new Thread(new ItemWriter(print), itemWriterName);
itemWriter.start();
Thread newLineWriter = new Thread(new NewLineWriter(print), newLineWriterName);
newLineWriter.start();
}
}
class ItemWriter implements Runnable {
private Printer print;
ItemWriter(Printer print) {
this.print = print;
}
public void run() {
while (print.current <= print.MAX) {
print.printNumber();
}
}
}
class NewLineWriter implements Runnable {
private Printer print;
NewLineWriter(Printer print) {
this.print = print;
}
public void run() {
while (print.current <= print.MAX) {
print.printNewLine();
}
}
}
class Printer {
public final int MAX;
public int current = 1;
public int itemsInALine = 1;
Printer(int max) {
this.MAX = max;
}
public void printNumber() {
synchronized(this) {
for(int i = current; i < current + itemsInALine && i <= MAX; i++) {
System.out.print(i + " ");
}
this.current = current + itemsInALine;
itemsInALine++;
notifyAll();
try {
if(this.current < MAX) {
wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void printNewLine() {
synchronized(this) {
System.out.println();
notifyAll();
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

How to execute four threads consecutively one by one in java? [duplicate]

I have 3 threads
1st printing A
2nd printing B
3rd printing C
I want to print in sequence A B C A B C A B C and so on.....
So I wrote the program below, but I am not able to achieve the same.
I am aware of the problem that when status=1 at that time say for example B1 and C1 thread are waiting and when I do notifyAll() both waiting thread wake up and depending on CPU allocation it might print B or C.
in this case I want only B to be printed after A.
what modification I need to do.
public class NotifyAllExample {
int status=1;
public static void main(String[] args) {
NotifyAllExample notifyAllExample = new NotifyAllExample();
A1 a=new A1(notifyAllExample);
B1 b=new B1(notifyAllExample);
C1 c=new C1(notifyAllExample);
a.start();
b.start();
c.start();
}
}
class A1 extends Thread{
NotifyAllExample notifyAllExample;
A1(NotifyAllExample notifyAllExample){
this.notifyAllExample = notifyAllExample;
}
#Override
public void run() {
try{
synchronized (notifyAllExample) {
for (int i = 0; i < 100; i++) {
if(notifyAllExample.status!=1){
notifyAllExample.wait();
}
System.out.print("A ");
notifyAllExample.status = 2;
notifyAllExample.notifyAll();
}
}
}catch (Exception e) {
System.out.println("Exception 1 :"+e.getMessage());
}
}
}
class B1 extends Thread{
NotifyAllExample notifyAllExample;
B1(NotifyAllExample notifyAllExample){
this.notifyAllExample = notifyAllExample;
}
#Override
public void run() {
try{
synchronized (notifyAllExample) {
for (int i = 0; i < 100; i++) {
if(notifyAllExample.status!=2){
notifyAllExample.wait();
}
System.out.print("B ");
notifyAllExample.status = 3;
notifyAllExample.notifyAll();
}
}
}catch (Exception e) {
System.out.println("Exception 2 :"+e.getMessage());
}
}
}
class C1 extends Thread{
NotifyAllExample notifyAllExample;
C1(NotifyAllExample notifyAllExample){
this.notifyAllExample = notifyAllExample;
}
#Override
public void run() {
try{
synchronized (notifyAllExample) {
for (int i = 0; i < 100; i++) {
if(notifyAllExample.status!=3){
notifyAllExample.wait();
}
System.out.print("C ");
notifyAllExample.status = 1;
notifyAllExample.notifyAll();
}
}
}catch (Exception e) {
System.out.println("Exception 3 :"+e.getMessage());
}
}
}
Convert those IF statements to WHILE statements to get the desired behavior:
if (notifyAllExample.status != 2){
notifyAllExample.wait();
}
to
while (notifyAllExample.status != 2){
notifyAllExample.wait();
}
This will ensure that if a thread is notified, it won't go out of the while loop until the status value is what it expects.
Also, mark status as volatile so that the threads won't have a local copy.
public class RunThreadsInOrder implements Runnable {
static int numThread = 1;
static int threadAllowedToRun = 1;
int myThreadID;
private static Object myLock = new Object();
public RunThreadsInOrder() {
this.myThreadID = numThread++;
System.out.println("Thread ID:" + myThreadID);
}
#Override
public void run() {
synchronized (myLock) {
while (myThreadID != threadAllowedToRun) {
try {
myLock.wait();
} catch (InterruptedException e) {
} catch (Exception e) {}
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println("myThreadID is running: " + myThreadID);
myLock.notifyAll();
threadAllowedToRun++;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t1 = new Thread(new RunThreadsInOrder());
Thread t2 = new Thread(new RunThreadsInOrder());
Thread t3 = new Thread(new RunThreadsInOrder());
Thread t4 = new Thread(new RunThreadsInOrder());
Thread t5 = new Thread(new RunThreadsInOrder());
Thread t6 = new Thread(new RunThreadsInOrder());
Thread t7 = new Thread(new RunThreadsInOrder());
t7.start();
t6.start();
t5.start();
t4.start();
t3.start();
t2.start();
t1.start();
}
}
public class Main {
public static void main(String[] args) throws IOException{
Thread t1 = new Thread(new A(), "1");
Thread t2 = new Thread(new A(), "2");
Thread t3 = new Thread(new A(), "3");
t1.start();
try{
t1.join();
}catch (Exception e){
}
t2.start();
try{
t2.join();
}catch (Exception e){
}
t3.start();
try{
t3.join();
}catch (Exception e){
}
}
}
class A implements Runnable{
public void run(){
System.out.println(Thread.currentThread().getName());
}
}
or you can use Executor Framework
public class Sequence {
int valve = 1;
public static void main(String[] args){
Sequence s = new Sequence();
ExecutorService es = Executors.newFixedThreadPool(3);
List<Runnable> rList = new ArrayList<>();
rList.add(new A(s));
rList.add(new B(s));
rList.add(new C(s));
for(int i = 0; i < rList.size(); i++){
es.submit(rList.get(i));
}
es.shutdown();
}
}
class A implements Runnable{
Sequence s;
A(Sequence s){
this.s = s;
}
public void run(){
synchronized (s) {
for (int i = 0; i < 10; i++) {
while (s.valve != 1) {
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("A");
s.valve = 2;
s.notifyAll();
}
}
}
}
class B implements Runnable{
Sequence s;
B(Sequence s){
this.s = s;
}
public void run() {
synchronized (s) {
for (int i = 0; i < 10; i++) {
while (s.valve != 2) {
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("B");
s.valve = 3;
s.notifyAll();
}
}
}
}
class C implements Runnable{
Sequence s;
C(Sequence s){
this.s = s;
}
public void run() {
synchronized (s) {
for(int i = 0; i < 10; i++) {
while (s.valve != 3) {
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("C");
s.valve = 1;
s.notifyAll();
}
}
}
}
In the first case the join for each thread causes the threads to wait for one another. In the second case a list stores the threads and executor executes them one after another creating 3 threads
Another way to do this is where only one runnable class is present and communication between thread is done via static variable in the main class and a variable in the runnable class
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Seq {
int i = 1;
public static void main(String[] args){
Seq s = new Seq();
Common c1 = new Common(s, 1);
Common c2 = new Common(s, 2);
Common c3 = new Common(s, 3);
List<Runnable> l = new ArrayList<>();
l.add(c1);
l.add(c2);
l.add(c3);
ExecutorService es = Executors.newFixedThreadPool(3);
for(int i = 0; i < 3; i++){
es.submit(l.get(i));
}
es.shutdown();
}
}
class Common implements Runnable{
Seq s;
int o;
Common(Seq s, int o){
this.s = s;
this.o = o;
}
public void run(){
synchronized (s) {
for (int z = 0; z < 100; z++) {
if(s.i > 3)
s.i = 1;
while (s.i != o) {
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(o);
s.i++;
s.notifyAll();
}
}
}
}
I was asked to write a similar program in an interview with the added condition that it should be extensible in a way that we can provide our own count of threads and they should print characters with the first thread printing 'A' and then the subsequent threads printing B, C, D and so on. Here's how I did it.
public class AlternateCharPrinter {
public static char ch = 65;
private static void createAndStartThreads(int count) {
Object lock = new Object();
for (int i = 0; i < count; i++) {
new Thread(new AlternateCharRunner((char) (65 + i), lock)).start();
}
}
public static void main(String[] args) {
createAndStartThreads(4);
}
}
class AlternateCharRunner implements Runnable {
private char ch;
private Object lock;
private static int runnerCount;
public AlternateCharRunner(char ch, Object lock) {
this.ch = ch;
this.lock = lock;
runnerCount++;
}
#Override
public void run() {
while (true) {
synchronized (lock) {
while (ch != AlternateCharPrinter.ch) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(AlternateCharPrinter.ch++);
if (AlternateCharPrinter.ch == (65 + runnerCount)) {
AlternateCharPrinter.ch = 65;
}
lock.notifyAll();
}
}
}
}
You need to replace
if (notifyAllExample.status!=1)
with
while (notifyAllExample.status!=1)
and same thing in the other 2 classes. If not, then as soon as the wait exits the thread continues without knowing if it is its turn.
Replace:
if(notifyAllExample.status!=1){
notifyAllExample.wait();
}
with:
while(notifyAllExample.status!=1){
notifyAllExample.wait();
}
in all classes accordingly.
The simplest solution to solve this can be following way:
public class PrintInOrder implements Runnable {
private int valueToPrint;
private int id;
private static int turn = 1;
private static int RESET_TURN_THRESHOLD = 3;
public PrintInOrder() {
this.valueToPrint = -1;
}
public PrintInOrder(int id, int val) {
this.id = id;
this.valueToPrint = val;
}
#Override
public void run() {
while(true) {
if (turn == this.id) {
System.out.println(Thread.currentThread().getName() + "::::" + valueToPrint);
turn++;
}
if (turn > RESET_TURN_THRESHOLD) {
turn = 1;
}
}
}
public static void main(String []args) {
Thread t1 = new Thread(new PrintInOrder(1, 1));
t1.setName("THREAD-1");
t1.start();
Thread t2 = new Thread(new PrintInOrder(2, 2));
t2.setName("THREAD-2");
t2.start();
Thread t3 = new Thread(new PrintInOrder(3, 3));
t3.setName("THREAD-3");
t3.start();
}
}
/*
OUTPUT::::
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
...
*/
Here is my solution -
I have created three threads each thread knows what it needs to print and what comes after it.
I have also created a Class NLock which holds the next word which needs to be printed.
Whenever a thread is able to acquire NLock lock then it checks
if it's his turn if yes then it prints the word and set the next value to be printed in NLock or else it waits till it's his turn
public class SynchronizeThreeThreads {
public static void main(String args[]) throws InterruptedException {
NLock lock=new NLock("A");
Thread a =new Thread(new PrintInOrder("A","B",lock));
Thread b =new Thread(new PrintInOrder("B","C",lock));
Thread c =new Thread(new PrintInOrder("C","A",lock));
a.start();
b.start();
c.start();
c.join(); // Once all is done main thread will exit
System.out.println("Done");
}
}
class NLock{
private String value;
public NLock(String value) {
this.value=value;
}
public String getValue() {
return value;
}
public void setValue(String next) {
this.value=next;
}
}
class PrintInOrder implements Runnable{
private String word;
private String next;
private NLock lock;
public PrintInOrder(String word, String next,NLock lock){
this.word=word;
this.next=next;
this.lock=lock;
}
#Override
public void run() {
int i=0;
while(i<3) {
synchronized (lock) {
try {
//Check if it's my turn
if(lock.getValue().equals(word)) {
System.out.println(this.word);
//Set what next needs to be printed
//So that when that thread wakes up it knows that it's his turn
lock.setValue(next);
i++;
lock.notifyAll();
Thread.sleep(100);
}
else //Nope not my turn wait
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Below is the output
A
B
C
A
B
C
A
B
C
Done
This is my attempt to solve the same. Any suggestions are welcome. This is the complete running code.
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
#Slf4j
public class SeqExecution {
static class SeqThread extends Thread {
private static final Object lock = new Object();
private static final AtomicInteger AUTO_COUNTER = new AtomicInteger();
private static final TrackExecution trackExecution = new TrackExecution();
private final int seqNo;
SeqThread(Runnable runnable) {
super(runnable);
this.seqNo = AUTO_COUNTER.getAndIncrement();
}
#SneakyThrows
#Override
public void run() {
while (true) {
synchronized (lock) {
while (trackExecution.CUR_EXECUTION.get() != this.seqNo) {
try {
lock.wait(100);
} catch (Exception e) {}
}
//log.info("Thread: {} is running", this.seqNo);
super.run();
sleep(1000);
trackExecution.increment();
lock.notifyAll();
}
}
}
static class TrackExecution {
private final AtomicInteger CUR_EXECUTION = new AtomicInteger();
int get() {
return CUR_EXECUTION.get();
}
synchronized void increment() {
var val = CUR_EXECUTION.incrementAndGet();
if (val >= SeqThread.AUTO_COUNTER.get()) {
CUR_EXECUTION.set(0);
}
}
}
}
public static void main(String[] args) {
final var seqThreads = List.of(new SeqThread(() -> System.out.print("A ")),
new SeqThread(() -> System.out.print("B ")),
new SeqThread(() -> System.out.print("C ")));
seqThreads.forEach(Thread::start);
seqThreads.forEach(t -> {
try {
t.join();
} catch (Exception e) {
log.warn(e.getMessage(), e);
}
});
}
}
I think it's simpler to achieve this using join.
Example:
public static void main(String[] args) {
final Thread t1 = new Thread("t1") {
#Override
public void run() {
System.out.println("i am thread: " + Thread.currentThread().getName());
}
};
final Thread t2 = new Thread(t1, "t2") {
#Override
public void run() {
t1.start();
try {
t1.join();
} catch ( InterruptedException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("i am thread: " + Thread.currentThread().getName());
}
};
Thread t3 = new Thread(t2, "t3") {
#Override
public void run() {
t2.start();
try {
t2.join();
} catch ( InterruptedException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("i am thread: " + Thread.currentThread().getName());
}
};
t3.start();
}
Here is my solution please try and let me know
package thread;
class SyncPrinter {
public static void main(String[] args) {
SyncPrinterAction printAction1 = new SyncPrinterAction(new int[]{1,5,9,13}, true);
SyncPrinterAction printAction2 = new SyncPrinterAction(new int[]{2,6,10,14}, true);
SyncPrinterAction printAction3 = new SyncPrinterAction(new int[]{3,7,11,15}, true);
SyncPrinterAction printAction4 = new SyncPrinterAction(new int[]{4,8,12,16}, false);
printAction1.setDependentAction(printAction4);
printAction2.setDependentAction(printAction1);
printAction3.setDependentAction(printAction2);
printAction4.setDependentAction(printAction3);
new Thread(printAction1, "T1").start();;
new Thread(printAction2, "T2").start();
new Thread(printAction3, "T3").start();
new Thread(printAction4, "T4").start();
}
}
class SyncPrinterAction implements Runnable {
private volatile boolean dependent;
private SyncPrinterAction dependentAction;
int[] data;
public void setDependentAction(SyncPrinterAction dependentAction){
this.dependentAction = dependentAction;
}
public SyncPrinterAction( int[] data, boolean dependent) {
this.data = data;
this.dependent = dependent;
}
public SyncPrinterAction( int[] data, SyncPrinterAction dependentAction, boolean dependent) {
this.dependentAction = dependentAction;
this.data = data;
this.dependent = dependent;
}
#Override
public void run() {
synchronized (this) {
for (int value : data) {
try {
while(dependentAction.isDependent())
//System.out.println("\t\t"+Thread.currentThread().getName() + " :: Waithing for dependent action to complete");
wait(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
dependentAction.setDependent(true);
System.out.println(Thread.currentThread().getName() + " :: " +value);
dependent = false;
}
}
}
private void setDependent(boolean dependent) {
this.dependent = dependent;
}
private boolean isDependent() {
return dependent;
}
}

Java: sync method how to synchronized with sync static method?

Code Snippet:
public class SyncTest {
public static void main(String[] args) {
new SyncTest().test();
}
private void test() {
final Outputer outputer = new Outputer();
// Thread 1
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
outputer.outPut("一二三四五六七八九");
}
}
}).start();
// Thread2
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
Outputer.outPut2("123456789");
}
}
}).start();
}
static class Outputer {
public void outPut( String name) {
int len = name.length();
synchronized (Outputer.this) { // lock is Outputer.class
for (int i = 0; i < len; i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
public static synchronized void outPut3( String name) { // lock also is Outputer.class
int len = name.length();
for (int i = 0; i < len; i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
Output :
123456789
1一2二三四五六七八九
3456789
obvious no synchronized, please give a hand, thanks
You need to specify the class instance instead of this, so both use the same Monitor object
static class Outputer {
public void outPut( String name) {
int len = name.length();
synchronized (Outputer.class) { // Outputer.this is not the same as Outputer.class
for (int i = 0; i < len; i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
alternatively you can use a seperate monitor object so thats explicit which will be used:
static class Outputer {
private static Object syncronisationMonitor = new Object();
// nonstatic method
public void outPut( String name) {
synchronized (syncronisationMonitor ) { // we use the same monitor as in the static method
[...]
}
}
//static method
public static void outPut3( String name) {
synchronized (syncronisationMonitor ) { // we use the same monitor as in the non-static method
[...]
}
}
}

Print RED BLUE GREEN in order using System.out.print

public class CyclicBar {
private final static CyclicBarrier cb = new CyclicBarrier(3,
new Runnable() {
#Override
public void run() {
System.out.println("\n-------------");
}
});
public static void main(String[] args) {
final class ColouredRunnable implements Runnable {
private int i;
public ColouredRunnable(int j) {
this.i = j;
}
#Override
public void run() {
final String name = Thread.currentThread().getName();
while (true) {
cyclicAwait();
for (int i = 0; i < name.length(); i++) {
sleep();
// System.out.print("" + name.charAt(i) + this.i + " ");
System.out.print("" + name.charAt(i) + " ");
}
}
}
}
;
int i = 0;
new Thread(new ColouredRunnable(i++), "RED").start();
new Thread(new ColouredRunnable(i++), "BLUE").start();
new Thread(new ColouredRunnable(i++), "GREEN").start();
}
private static int cyclicAwait() {
try {
return cb.await();
} catch (InterruptedException | BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return -1;
}
private static void sleep() {
try {
Thread.sleep(ThreadLocalRandom.current().nextLong(200, 600));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Above code currently prints
-------------
G R B R E L E E D U E N
-------------
B R G E R L U E D E E N
-------------
R G B E L R E U D E E N
-------------
R G B E R L U E D E E N
-------------
B R G E L D R U E E E N
-------------
How to alter above code and add proper barrier at appropriate location to produce following output
-------------
R E D B L U E G R E E N
-------------
R E D B L U E G R E E N
-------------
R E D B L U E G R E E N
Constraints
Must use one of modern java concurrent higher level Objects
Should not use implicit locking synchronised wait notify
must print individual characters using System.out.print()
use 3 thread with each thread must print its name (colour)
It should be printed in the order RED BLUE GREEN
public class TestSynMain {
private final static AbstractQueuedSynchronizer cb = new TestSynchronizer(6);
public static void main(String[] args) {
final class ColouredRunnable implements Runnable {
private String color;
public ColouredRunnable(String color) {
this.color = color;
}
#Override
public void run() {
while (true) {
try {
boolean result = false;
do{
result = cb.tryAcquireNanos(Integer.parseInt(Thread.currentThread().getName()), TimeUnit.MILLISECONDS.toNanos(1000));
}while(!result);
for (int i = 0; i < color.length(); i++) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
System.exit(-1);
}
System.out.print("" + color.charAt(i) + " ");
}
} catch (NumberFormatException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}finally{
cb.release(Integer.parseInt(Thread.currentThread().getName()));
}
}
}
}
new Thread(new ColouredRunnable("RED"), "0").start();
new Thread(new ColouredRunnable("BLUE"), "1").start();
new Thread(new ColouredRunnable("GREEN"), "2").start();
new Thread(new ColouredRunnable("BLACK"), "3").start();
new Thread(new ColouredRunnable("MAGENTA"), "4").start();
new Thread(new ColouredRunnable("WHITE"), "5").start();
}
}
public class TestSynchronizer extends AbstractQueuedSynchronizer{
/**
*
*/
private static final long serialVersionUID = 1L;
int count;
public TestSynchronizer(int count) {
this.count = count;
setState(0);
}
#Override
protected boolean tryAcquire(int arg) {
if(arg == getState()){
System.out.println("Acquires" + Thread.currentThread().getName());
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
#Override
protected boolean tryRelease(int arg) {
int state = getState();
setState(++state % count);
setExclusiveOwnerThread(null);
return true;
}
}
How to use it?
Synchronizer takes one argument count that is for upto how many threads have to synchronize.
The names of the threads MUST be the order they need to take. Now you can add as many threads to it as you need.
I have designed a custom Synchronizer and used that to define a new policy for allowing locking and unlocking of threads.
Phasers are pretty cool for this too if you want to play with them. All this one requires is that you populate the words list with whatever words you want - it makes a thread for each word and they all play nicely.
public class PhaserTest
{
private final Phaser phaser = new Phaser(1) {
protected boolean onAdvance(int phase, int parties)
{
//Phaser version of your CyclicBarrier Runnable
if(parties == 1)
System.out.println("\n-------------");
return false;
}
};
public void runTest()
{
List<String> words = Arrays.asList("RED", "BLUE", "GREEN");
for(int i = 0; i < words.size();i++)
new Thread(new ColouredRunnable(words.get(i),i + 1)).start();
while(phaser.arriveAndAwaitAdvance() != (words.size() + 1)){}
System.out.println("Done.");
}
public class ColouredRunnable implements Runnable {
private final int order;
private final String color;
public ColouredRunnable(String s, int order) {
this.color = s;
this.order = order;
phaser.register();
}
#Override
public void run() {
while(phaser.arriveAndAwaitAdvance() != order){}
for (int i = 0; i < color.length(); i++) {
sleep();
System.out.print("" + color.charAt(i) + " ");
}
phaser.arriveAndDeregister();
}
private void sleep() {
try {
Thread.sleep(ThreadLocalRandom.current().nextLong(200, 600));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
This solution uses 3 cyclic barriers. Code initially creates a managed deadlock between threads using cyclic barriers. Deadlock is broken by triggering cb[cb.length-1].await(); in main thread
public static void main(String[] args) {
String colors[] = { "RED", "BLUE", "GREEN" };
final CyclicBarrier[] cb = createCB(colors);
for (int i = 0; i < colors.length; i++) {
final int j = i;
new Thread(colors[i]) {
public void run() {
while (true) {
try {
cb[(j == 0 ? cb.length : j) - 1].await();// Wait for
// previous
// barrier
String name = getName();
for (int i = 0; i < name.length(); i++) {
CyclicBari.sleep();
System.out.print(" " + name.charAt(i) + " ");
}
cb[j].await();// Notify next
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
}.start();
}
System.out.println("start");
try {
cb[cb.length-1].await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
private static void sleep() {
try {
Thread.sleep(ThreadLocalRandom.current().nextLong(200, 600));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static CyclicBarrier[] createCB(String[] colors) {
final CyclicBarrier cb[] = new CyclicBarrier[colors.length];
for (int i = 0; i < cb.length; i++) {
final int j = i;
cb[i] = new CyclicBarrier(2, new Runnable() {
#Override
public void run() {
if (j == cb.length - 1) {
System.out.println("\n-------------");
} else {
System.out.print(".");
}
}
});
}
return cb;
}
Output
-------------
R E D . B L U E . G R E E N
-------------
R E D . B L U E . G R E E N
-------------
R E D . B L U E . G R E E N
-------------

Threads: How to put a check inside Thread Consumer for Data reciving check

I have this producer Consumer sample Program shown below
How can i put a Condition inside my Consumer Thread class so that if i didn't recivied the data from producer for 1 minute , i need to log that ??
This is my Producer Consumer Program
public class ProducerConsumerTest {
public static void main(String[] args) {
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
class CubbyHole {
private int contents;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {
wait();
} catch (InterruptedException e) {
}
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
} catch (InterruptedException e) {
}
}
contents = value;
available = true;
notifyAll();
}
}
class Producer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Producer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
while(true)
{
for (int i = 0; i < 100000; i++) {
cubbyhole.put(i);
System.out.println("Producer #" + this.number + " put: " + i);
try {
sleep((int) (Math.random() * 2000));
} catch (Exception e) {
}
}
}
}
}
class Consumer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Consumer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
while(true)
{
int value = 0;
for (int i = 0; i < 100000; i++) {
value = cubbyhole.get();
System.out.println("Consumer #" + this.number + " got: " + value);
}
}
}
}
Could anybody please help
You could use Object#wait(long timeout) and log from inside the get() method:
try {
wait(60 * 1000);
if (available == false) {
//log
}
} catch (InterruptedException e) {
}
Use System.currentTimeMilis() in your Consumer run method:
long before;
for (int i = 0; i < 100000; i++) {
before = System.currentTimeMilis();
value = cubbyhole.get();
if (System.currentTimeMilis() - before > 1000 * 60) {
System.out.println("Consumer waited for more than one minute");
}
System.out.println("Consumer #" + this.number + " got: " + value);
}

Categories