Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 18 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
18
Dung lượng
0,98 MB
Nội dung
Lab Guide Lab version:1.0.0 Last updated:9/7/2015 Page Overview Java has built-in support for concurrent programming by running multiple threads concurrently within a single program A thread, also called a lightweight process, is a single sequential flow of programming operations, with a definite beginning and an end During the lifetime of the thread, there is only a single point of execution A thread by itself is not a program because it cannot run on its own Instead, it runs within a program The following figure shows a program with threads running under a single CPU: Objectives Once you have completed this lab, you will understand: Benefit of using of thread How to write and handle a multithread program Exercises This Hands-On Lab is comprised by the following exercises: Use the Thread class Runable Interface Using some of thread methods Synchronization Thread Priority Estimated time to complete this lab: hours Page Index EXERCISE 1: USE THE THREAD CLASS Task - Create RunThread class extending Thread class Task - Main program Task - Execute your program EXERCISE 2: IMPLEMENT THE RUNABLE INTERFACE Task - Create RunThread class Implement Runable Interface Task - Main program Task - Execute your program EXERCISE 3: USING JOIN() TO WAIT FOR THREADS TO FINISH Task - Create MyThread class Implement Runable Interface Task - Main program Task - Execute your program EXERCISE 4: 10 THREAD PRIORITY 11 Task - Create clicker class Implement Runable Interface 11 Task - Main program 12 Task - Execute your program 13 EXERCISE 5: SYNCHRONIZATION 13 Task - Create CountPrimesThread class extending Thread class 13 Task - Write code in CountPrimesThread.java 13 Task - Create a running Program 14 Task - Execute your program 16 Task - Change your program to make speed up your program: 17 Page Page Next Step Exercise 1: Use the Thread class Task - Create RunThread class extending Thread class In the "Package Explorer" (left panel) ⇒ Right-click on your Project (or use the "File" menu) ⇒ New ⇒ Class The "New Java Class" dialog pops up In "Name" field, enter “RunThread" In SupperClass field, enter “Exception” Click "Finish" Write code for RunThread Class private String toSay; private int Sleep; public RunThread(String st,int sl){ toSay = st; Sleep=sl; } public void run(){ try{ for(int i=1;i 0; i ) { System.out.println(name + ": " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(name + " interrupted."); } System.out.println(name + " exiting."); } } Task - Main program In this task you will write code to demonstrate using of join method In the "Package Explorer" (left panel) ⇒ Right-click on your Project (or use the "File" menu) ⇒ New ⇒ Class The "New Java Class" dialog pops up In "Name" field, enter "MainClass" Check "public static void main(String[] args)" box Click "Finish" Write code for main() method MyThread ob1 = new MyThread("One"); MyThread ob2 = new MyThread("Two"); MyThread ob3 = new MyThread("Three"); System.out.println("Thread One is alive: " + ob1.t.isAlive()); System.out.println("Thread Two is alive: " + ob2.t.isAlive()); System.out.println("Thread Three is alive: " + ob3.t.isAlive()); try { System.out.println("Waiting for threads to finish."); ob1.t.join(); ob2.t.join(); ob3.t.join(); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Thread One is alive: " + ob1.t.isAlive()); System.out.println("Thread Two is alive: " + ob2.t.isAlive()); Page System.out.println("Thread Three is alive: " + ob3.t.isAlive()); System.out.println("Main thread exiting."); } Task - Execute your program To run the program, right-click anywhere on the source file "MainClass.java" (or from the "Run" menu) ⇒ Choose "Run As" ⇒ "Java Application" The output appears on the "Console" panel Page 10 Exercise 4: Thread priority Task - Create clicker class Implement Runable Interface In the "Package Explorer" (left panel) ⇒ Right-click on your Project (or use the "File" menu) ⇒ New ⇒ Class The "New Java Class" dialog pops up In "Name" field, enter “clicker" In Interface field, press “Add” button, Enter Runable and press Add Click "Finish" Write code for clicker Class long click = 0; Thread t; private volatile boolean running = true; public clicker(int p) { t = new Thread(this); t.setPriority(p); } public void run() { while (running) { click++; } } public void stop() { running = false; } public void start() { t.start(); } Page 11 Task - Main program In the "Package Explorer" (left panel) ⇒ Right-click on your Project (or use the "File" menu) ⇒ New ⇒ Class The "New Java Class" dialog pops up In "Name" field, enter "HiLoPri" Check "public static void main(String[] args)" box Click "Finish" Write code for main() method public static void main(String args[]) { Thread.currentThread().setPriority(Thread.MAX_PRIORITY); clicker hi = new clicker(Thread.NORM_PRIORITY + 2); clicker no = new clicker(Thread.NORM_PRIORITY); clicker lo = new clicker(Thread.NORM_PRIORITY - 2); lo.start(); no.start(); hi.start(); try { Thread.sleep(5000); } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } lo.stop(); no.stop(); hi.stop(); // Wait for child threads to terminate try { hi.t.join(); no.t.join(); lo.t.join(); } catch (InterruptedException e) { System.out.println("InterruptedException caught"); } System.out.println("Low-priority thread : " + lo.click); System.out.println("Normal-priority thread: " + no.click); System.out.println("High-priority thread : " + hi.click); } Page 12 Task - Execute your program To run the program, right-click anywhere on the source file "HiLoPri.java" (or from the "Run" menu) ⇒ Choose "Run As" ⇒ "Java Application" The output appears on the "Console" panel Set other priority for each thread and see the output result Exercise 5: Synchronization The program in this exercise will demonstrate the usage of synchronization to count the number of prime integers between and 1000000 The work can be divided among one to five threads, where the number of threads required to search the prime numbers will be decided by the user Task - Create CountPrimesThread class extending Thread class In the "Package Explorer" (left panel) ⇒ Right-click on your Project (or use the "File" menu) ⇒ New ⇒ Class The "New Java Class" dialog pops up In "Name" field, enter “CountPrimesThread" In SupperClass field, enter “Thread” Click "Finish" Task - Write code in CountPrimesThread.java Class variables //Variable to store the number of primes in a specified range of static int count = 0; // Variable to store the range of minimum and maximum integer value int min, max; Page 13 Create constructors public CountPrimesThread(int min, int max) { this.min = min; this.max = max; } isPrime() method is invoked to test whether x is a prime number or not private static boolean isPrime(int x) { int top = (int)Math.sqrt(x); for(int i = 2;i 5); countPrimesWithThreads(numberOfThreads); } Page 15 Task - Execute your program To run the program, right-click anywhere on the source file " SynchronizeSearch.java" (or from the "Run" menu) ⇒ Choose "Run As" ⇒ "Java Application" The output appears on the "Console" panel And Try Again Page 16 Add synchronized keyword to countPrimes method and run again Task - Change your program to make speed up your program: Add addcount method to CountPrimesThread class synchronized private static void addcount(int x) { count=count+x; } Change CountPrimes() method private static void countPrimes(int min, int max) { int x=0; for(int i = min;i