Friday, May 25, 2012

1.5 Threads and Multithreading

Starting and Running Multiple Threads


Let’s actually get down to business and get multiple threads going (more than two, that is). We already had two threads, because the main() method starts in a thread of its own, and then t.start() started a second thread. Now we’ll do more. The following code creates a single Runnable instance and three Thread instances. All three Thread instances get the same Runnable instance, and each thread is given a unique name. Finally, all three threads are started by invoking start() on the Thread instances.



class TestRunnableWithNames implements Runnable {

public void run() {

for (int x = 1; x <= 3; x++) {
System.out.println("Run by "

+ Thread.currentThread().getName()

+ ", x is " + x);

}

}

}

public class ManyNames {

public static void main(String [] args) {

// Make one Runnable

TestRunnableWithNames nr = new TestRunnableWithNames();

Thread one = new Thread(nr);

Thread two = new Thread(nr);

Thread three = new Thread(nr);



one.setName("Rocky");

two.setName("Cena");

three.setName("Triple H");

one.start();

two.start();

three.start();

}

}

Running this code might produce the following:



% java ManyNames

Run by Rocky, x is 1

Run by Triple H, x is 1

Run by Rocky, x is 2

Run by Cena, x is 1

Run by Rocky, x is 3

Run by Cena, x is 2

Run by Cena, x is 3

Run by Triple H, x is 2

Run by Triple H, x is 3



Well, at least that’s what it printed when we ran it—this time, on our machine. But the behavior you see above is not guaranteed. I repeat, “THE BEHAVIOR IS NOT GUARANTEED.” You need to know, for your future as a Java programmer as well as for the exam, that there is nothing in the Java specification that says threads will start running in the order in which they were started (in other words, the order in which start() was invoked on each thread). And there is no guarantee that once a thread starts executing, it will keep executing until it’s done. Or that a loop will complete before another thread begins. Nothing is guaranteed in the preceding code except this:

No comments:

Post a Comment

java-8-streams-map-examples

package com.mkyong.java8; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; im...