-1

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 ??

Mokbor
  • 1
  • This doesn't make sense to me. Can you describe what you really want? – Stefan Falk Feb 05 '15 at 17:57
  • 3
    This is way more complicated than what you think, you would need to use `ThreadPool` and implement an `algorithm` to block and wait. The normaly `wait` function of `Thread` won't do it. – Jean-François Savard Feb 05 '15 at 17:58
  • I need to write on console abcdabcdab.... from String[] s = { "aaaaaaa", "bbbb", "ccc", "dd" };. I have to use only one thread for one letter( one for a, one for b, one for c.....) – Mokbor Feb 05 '15 at 18:20
  • um ... using 4 threads for a FIXED execution order makes no sense - simply use one single thread which repeatedly executes in your predefined order; it will me much easier if you pre-process the to-be-executed list of elements and pass it into your thread. – specializt Feb 05 '15 at 19:16
  • Threads exist for two reasons: (1) respond to different asynchronous external events, (2) implement parallel computations on a multi-processor machine. In either case, what makes threads useful is that the _order of the computation steps performed by different threads does not matter_. Threads always need to be synchronized at _some_ level, but the higher the better. The more tightly you couple the threads, the less benefit you get from multi-threading. If you need your threads to be synchronized at every step, then there is no benefit at all: You should not be using threads. – Solomon Slow Feb 05 '15 at 20:19

2 Answers2

0

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
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
  • what is "And Status Counter is cyclic to print in order" supposed to mean? – specializt Feb 05 '15 at 19:17
  • In each thread class i am changing the status to next status and at last thread , I set that counter again to 1 So that again thread 1 start to execute , Hope it clears what it supposed to mean – Neeraj Jain Feb 05 '15 at 19:23
  • Thank you, its ok, but is FIXED for 4 letters, i need to protect my program from more than 4 letter, when i take 10 lestters i need to create 6 threads more. And in your think is small problem, u need `a a` more on the end – Mokbor Feb 05 '15 at 19:44
0

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();
            }

        }

    }

}
Mokbor
  • 1