2

I have written this simple code to test the Runnable interface.

    import java.util.List;
    import java.util.ArrayList;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ExecutorService;
    class myClass implements Runnable{
      private final List< String >[] ls;
      private int n;
      public myClass(int m) 
      { 
        n = m;
        ls = new List[n];
        for (int i = 0; i < n; i++) {
          ls[i] = new ArrayList<>();
        }
      }
      public void run()
      {
        try {
          for (int i = 0; i < n; i++) {
            pleasePrint( ls[i] );
          } 
        } catch (Exception e) {
            System.out.println("error");
        }
      }
      public void init() {

        ls[0].add("1");  ls[0].add("2");  ls[0].add("3");
        ls[1].add("4");  ls[1].add("5");  ls[1].add("6");
      }
      void pleasePrint( List< String > ss )
      {
        for (int i = 0; i < ss.size(); i++) {
          System.out.print(ss.get(i)); // print the elements of one list
        }
      }
    }

    public class Threadtest {
      public static void main(String[] args) {
        myClass mc = new myClass(2);
        mc.init();
        ExecutorService te = Executors.newCachedThreadPool();
        te.execute(mc);
        te.shutdown();
      }
    }

As I run the code, it will print 123456. How can I be sure that two threads are run in parallel? With the given output maybe they are running in serial mode!

mahmood
  • 23,197
  • 49
  • 147
  • 242
  • There is only one thread that is being executed – Bilesh Ganguly May 20 '17 at 09:31
  • Because there is one ExecutorService? That two lists should represent two threads. How can I fix that? – mahmood May 20 '17 at 09:35
  • You can `submit()` multiple tasks to an ExecutorService. I'm writing it in the answer. Maybe it will help. – Bilesh Ganguly May 20 '17 at 09:37
  • To print both list in different threads, you would need to change the approach. The loop which calls `pleasePrint()` needs to spawn a new thread each time to do so. – Bilesh Ganguly May 20 '17 at 09:52
  • I tried similar thing http://stackoverflow.com/questions/44069194/using-runnable-to-run-a-method-by-multiple-threads – mahmood May 20 '17 at 10:01
  • It doesn't make any sense to "test an interface." An interface basically is just a declaration that any class that `implements` it must have certain methods. E.g., any class that implements `Runnable` must have a `void run()` method. It looks like what you're really trying to test here is the `ExecutorService`. – Solomon Slow May 21 '17 at 13:21

2 Answers2

2

In the example you gave, only one thread is being initiated.

To submit multiple tasks to an ExecutorService use the submit() method:

ExecutorService te = Executors.newCachedThreadPool();
te.submit(task);
te.submit(anotherTask);
// Some code
te.shutdown();

To check (for learning purpose) if the threads are distinct print the thread's name in run():

String name = Thread.currentThread().getName();

Solution of the top of my head:

public void run() {
    String name = Thread.currentThread().getName();
    System.out.println(name);

    // Do Something
}

If I submit the same instance to ExecutorService twice:

public static void main(String[] args) {
    myClass mc = new myClass(2);
    mc.init();
    ExecutorService te = Executors.newCachedThreadPool();
    te.submit(mc);
    te.submit(mc);
    te.shutdown();
}

Then output:

pool-1-thread-1
1
2
3
4
5
6
pool-1-thread-2
1
2
3
4
5
6

Note: I changed print() to println() and printed the name of the thread in run().

Hope this helps.


Update #1

To print the lists from different threads, you would need to change the approach. The loop which calls pleasePrint() instead needs to spawn a new thread and then calls this method from that thread.

Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58
0

How can I be sure that two threads are run in parallel?

You know that two threads are running concurrently if you know that both of them started before either one of them finished.

Print out a message when each thread starts, and print out a message when each thread ends. If you see both start messages before you see either end message, then you know that both threads were runnable during the interval between the second start message and the first end message.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57