CIS 260 Creating ThreadsOne possible answer to our problem is to use threads. This next example explores the use of threads by creating a couple of threads and seeing how they behave. One of the easiest ways to create threads is to create a subclass of Thread. After the threads are created, the code must call their start() methods to get them running. The primary method you are concerned with is run(). This is the workhorse method for threads and they will end when they exit their run() method. public class TThread2 { public static void main( String args[] ) { PThread t1, t2; t1 = new PThread(); t2 = new PThread(); System.out.println( "Starting threads" ); t1.start(); t2.start(); System.out.println( "Threads started" ); System.out.println( "Mainline finished" ); } } class PThread extends Thread { public PThread() { System.out.println( "Name: " + getName() + " being created"); } public void run() { System.out.println( getName() + " finished" ); } } // Name: Thread-0 being created // Name: Thread-1 being created // Starting threads // Threads started // Mainline finished // Thread-0 finished // Thread-1 finished |