//Thread1.java //A program can consist of multiple threads of execution, //coordinating together to do multiple tasks at once. //If multiprocessor, could be running simultaneously on separate CPUs. //In uniprocessor, the threads can take turns at the CPU, thus lengthy //task won't hold back others. //Parallel/concurrent processing within the program. //A thread is a lightweight process with its own call stack. //The threads share the same memory space. //Java has threading built-in to the language. //Runnable interface has run() class X implements Runnable { public void run() { //the required implementation //a thread has a getName() //Thread.currentThread() static method of Thread class refers to the execting thread System.out.println( "hi from a X thread. My name is " + Thread.currentThread().getName() ); } //other methods and fields...called by run() (or whomever if not being //run by a thread). } public class Threads1 { public static void main( String[] args ) { //1. instantiate the Runnable class: X x1 = new X(); //an X object is the "work" to be done. //2. instantiate a Thread with your Runnable object as its "target": Thread t = new Thread( x1 ); //a thread is spun off to do the work in. //the work is done by the thread. //3. start the thread. start() of Thread class. t.start(); //will call the Runnable's run() //main is a thread. It and the t thread are running concurrently, //as if in parallel. //main does NOT wait until the start() call returns. main continues. //main thread and the t thread are sharing the processor. //the order in which threads execute is indeterminate. //main thread's name is main System.out.println( "hi from " + Thread.currentThread().getName() ); //the x1 "job" can be given to many threads: Thread t2 = new Thread( x1 ); Thread t3 = new Thread( x1 ); Thread t4 = new Thread( x1 ); //a thread has a setName() to replace the boring default name t2.setName( "gilligan" ); t3.setName( "professor" ); t4.setName( "his wife" ); t2.start(); t3.start(); t4.start(); } }