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