UseThreads.java// Create a thread by implementing Runnable.
class MyThread implements Runnable {
String thrdName;
MyThread(String name) {
thrdName = name;
}
// Entry point of thread.
public void run() {
System.out.println(thrdName + " starting.");
try {
for(int count=0; count < 10; count++) {
Thread.sleep(400);
System.out.println("In " + thrdName +
", count is " + count);
}
}
catch(InterruptedException exc) {
System.out.println(thrdName + " interrupted.");
}
System.out.println(thrdName + " terminating.");
}
}
class UseThreads {
public static void main(String[] args) {
System.out.println("Main thread starting.");
// First, construct a MyThread object.
MyThread mt = new MyThread("Child #1");
// Next, construct a thread from that object.
Thread newThrd = new Thread(mt);
// Finally, start execution of the thread.
newThrd.start();
for(int i=0; i < 50; i++) {
System.out.print(".");
try {
Thread.sleep(100);
}
catch(InterruptedException exc) {
System.out.println("Main thread interrupted.");
}
}
System.out.println("Main thread ending.");
}
}
C:\ece538\java_thread>java UseThreads Main thread starting. .Child #1 starting. ...In Child #1, count is 0 ....In Child #1, count is 1 ....In Child #1, count is 2 ....In Child #1, count is 3 ....In Child #1, count is 4 ....In Child #1, count is 5 ....In Child #1, count is 6 ....In Child #1, count is 7 ....In Child #1, count is 8 ....In Child #1, count is 9 Child #1 terminating. ..........Main thread ending.
Maintained by John Loomis, updated Sat Nov 17 18:14:48 2012