0

I want to create three threads and print result of these threads alternately.

In this post,3 threads to print alternate values in sequence threads operates the same task. What i try to do is ,

//Thread Practice
//one number ,one char ,one string comining these two parallely
class Thread_1 extends Thread {

  public void run() {
    for (int i = 0; i < 10; i++) {
      System.out.println(Thread.currentThread().getId() + "... " + i);
      try {
        Thread.sleep(1000);
      } 
     catch (InterruptedException ex) {
             }
       }
    }
}

class Thread_2 extends Thread {
  String s = new String("ABCDEFGHIJ");

  public void run() {
    for (int i = 0; i < 10; i++) {
      System.out.println(Thread.currentThread().getId() + ".. " + s.charAt(i));
      try {
        Thread.sleep(1000);
      } catch (InterruptedException ex) {
      }
    }
  }
}

class Thread_3 extends Thread {
  String s = new String("ABCDEFGHIJ");

  public void run() {
    for (int i = 0; i < 10; i++) {
      System.out.println(Thread.currentThread().getId() + ".. " + i + s.charAt(i));
      try {
        Thread.sleep(1000);
      } catch (InterruptedException ex) {
      }
    }
  }
}

class Practice {
  public static void main(String[] args) {
    Thread_1 t1 = new Thread_1();
    Thread_2 t2 = new Thread_2();
    Thread_3 t3 = new Thread_3();

    t1.start();
    t2.start();
    t3.start();
  }
}

I want output to be 1 ,A, 1A then 2,B,2B and so on ,that is these threads should run alternately.With Sleep() ,the order is not guaranteed.

Can I achieve ordering over these threads to make them run alternately to get the desired output I want.(Purpose is learning insites of Threading).

Community
  • 1
  • 1
  • 1
    Fix your indentation. Your code's needlessly difficult to read. – khelwood Mar 03 '17 at 15:14
  • I guess you are looking for locks - see the [official tutorial](https://docs.oracle.com/javase/tutorial/essential/concurrency/newlocks.html) – UnholySheep Mar 03 '17 at 15:18
  • "Purpose is learning insites of Threading" This is a really bad example to try to learn about multithreading, because the best solution is to do it in just one thread. You'd be better served finding a problem with some actual concurrent requirement. – Andy Turner Mar 03 '17 at 15:21

0 Answers0