diff --git a/Chapter11/Creating_a_Thread_annotated.java b/Chapter11/Creating_a_Thread_annotated.java index 6b97a51..311e08f 100644 --- a/Chapter11/Creating_a_Thread_annotated.java +++ b/Chapter11/Creating_a_Thread_annotated.java @@ -1,8 +1,19 @@ -// To create a new thread, your program will either extend Thread or implement the Runnable interface. +// Java defines two ways in which you can create a runnable object: +// You can implement the Runnable interface or you can extend the Thread class. class MyThread202310 implements Runnable{ + + String thread_nameString; + + public MyThread202310(String thread_nameString) { + + this.thread_nameString = thread_nameString; + + } + // Inside run(), you can write some code that constitutes a thread. main() is a thread, too. public void run() { + System.out.println(thread_nameString + " starting."); } @@ -15,10 +26,12 @@ public class Creating_a_Thread_annotated { public static void main(String[] args) { System.out.println("Main thread starting."); - // To create another thread from within the main thread, construct a MyThread object first. - + // Create a runnable object. MyThread202310's object is runnable because it has run() method. + MyThread202310 myThread202310 = new MyThread202310("Child #1"); - Thread newtThread = new Thread(); + // You create a thread by instantiating an object of type Thread whose constructor encapsulates an object + // that is runnable. + Thread newtThread = new Thread(myThread202310); // newtThread.setContextClassLoader(myThread2023); }