Professional Documents
Culture Documents
Session Objectives
In this session, you will be practicing with Creating Threads Thread States Methods of Thread class Managing Threads Daemon Threads
2009 FPT-Aptech
Page 1 / 5
public class Race { public static void main(String a[]){ //create an array of runnable RaceCar objects RaceCar[] cars = new RaceCar[5]; cars[0] = new RaceCar(10, "Mario"); cars[1] = new RaceCar(10, "Songuku"); cars[2] = new RaceCar(10, "Herman"); cars[3] = new RaceCar(10, "Doremon"); cars[4] = new RaceCar(10, "Hoang Phi Hong"); //start racing for(int i=0; i<5; i++) cars[i].start(); } } 2. Create new thread class by implementing the interface Runnable. (15 minutes) The following program demonstrates another technique for creating threads. Perform the same procedure for the program below: class Mosquito implements Runnable { private int id; public Mosquito(int id){ this.id = id; } // implement the run() method for flying logic public void run(){ if (id == 12) { try { Thread.sleep(10000); } catch(Exception e){} } for (int i=0; i<10; i++){ System.out.println("The mosquito " + id + is running); }
2009 FPT-Aptech
Page 2 / 5
2009 FPT-Aptech
Page 3 / 5
Java Programming II-Lab1-Thread 1.2. Write a program to create the ouput as following figure:
Create three threads and the main thread. Execute each thread as simultaneous tasks. Display information when exiting each thread. 1.3. Create a new thread class that prints a value in duration. Information about a thread includes: message, duration, priority.
MESSAGE BOARD ==================== Number of messages: 2 Message 1: multithreading Timeout: 1000 Priority: high Message 2: multitasking Timeout: 2000 Priority: medium Result: Multithreading Multithreading Multitasking
2009 FPT-Aptech
Page 4 / 5
2009 FPT-Aptech
Page 5 / 5