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!