Lab Exercises
- Exercise 1: Extending Thread class (30 minutes)
- Exercise 2: Implementing Runnable interface (30 minutes)
- Exercise 3: ThreadGroup, ThreadPriority, View all threads (30 minutes)
- Exercise 4: Synchronization (30 minutes)
- Exercise 5: Inter-thread communication (30 minutes)
- Exercise 6: Timer and TimerTask (15 minutes)
- Homework Exercise (for people who are taking Sang Shin’s “Java Programming online course”)
Exercise 1: Extending Thread class
- The start() method is not in the constructor of the subclass
- The start() method is in the constructor of the subclass
(1.1) The start() method is not in the constructor of the subclass
1. Create a new NetBeans project
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects.
- Click Next.
- Under Name and Location pane, for the Project Name field, type in ExtendThreadClassTest0 as project name.
- For Create Main Class field, type in ExtendThreadClassTest0. (Figure-1.10 below)
- Click Finish.
Figure-1.10: Create a new project
- Observe that ExtendThreadClassTest0 project appears and IDE generated ExtendThreadClassTest0.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated ExtendThreadClassTest0.java as shown in Code-1.11 below. Study the code by paying special attention to the bold fonted parts. Note that the start() is invoked after the object instance of PrintNameThread class is created.
public class ExtendThreadClassTest0 {
public static void main(String args[]) { // Create object instance of a class that is subclass of Thread class // Start the thread by invoking start() method } |
Code-1.11: ExtendThreadClassTest0.java
3. Write PrintNameThread.java as shown in Code-1.12 below.
// Subclass extends Thread class public class PrintNameThread extends Thread { PrintNameThread(String name) { // Override the run() method of the Thread class. for (int i = 0; i < 10; i++) { |
Code-1.12: PrintNameThread.java
4. Build and run the project
- Right click ExtendThreadClassTest0 project and select Run.
- Observe the result in the Output window. (Figure-1.13 below)
Creating PrintNameThread object instance.. Calling start() method of A thread run() method of the A thread is called AAAAAAAAAA |
Figure-1.13: Result of running ExtendThreadClassTest0 application
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javathreads/samples/ExtendThreadClassTest0. You can just open it and run it.
5. Modify the ExtendThreadClassTest0.java as shown in Code-1.15 below. The code fragments that need to be added are highlighted in bold and blue-colored font.
public class ExtendThreadClassTest0 {
public static void main(String args[]) { // Create object instance of a class that is subclass of Thread class // Start the thread by invoking start() method System.out.println(“Creating PrintNameThread object instance..”); System.out.println(“Creating PrintNameThread object instance..”); |
Code-1.15: Modified ExtendThreadClassTest0.java
6. Build and run the project
- Right click ExtendThreadClassTest0 project and select Run.
- Observe the result in the Output window. (Figure-1.16 below)
Creating PrintNameThread object instance.. Calling start() method of A thread Creating PrintNameThread object instance.. Calling start() method of B thread AAAAAAAAAACreating PrintNameThread object instance.. BCalling start() method of C thread BBBBBBBBBCCCCCCCCCC |
Figure-1.16: Result
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javathreads/samples/ExtendThreadClassTest1. You can just open it and run it.
7. For your own exercise, modify ExtendThreadClassTest0.java as following. Build and run the application.
- Create and start another thread.
- Set the name of the thread as “MyOwn”
(1.2) The start() method is in the constructor of the subclass
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in ExtendThreadClassTest2 as project name.
- For Create Main Class field, type in ExtendThreadClassTest2.
- Click Finish.
- Observe that ExtendThreadClassTest2 project appears and IDE generated ExtendThreadClassTest2.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated ExtendThreadClassTest2.java as shown in Code-1.21 below.
public class ExtendThreadClassTest2 {
public static void main(String args[]) { PrintNameThread pnt1 = PrintNameThread pnt2 = PrintNameThread pnt3 = } |
Code-1.21: ExtendThreadClassTest2.java
3. Write PrintNameThread.java as shown in Code-1.22 below. Note that the start() method is invoked as part of the constructor method of the PrintNameThread class.
public class PrintNameThread extends Thread {
PrintNameThread(String name) { public void run() { |
Code-1.22: PrintNameThread.java
4. Build and run the project
- Right click ExtendThreadClassTest2 project and select Run.
- Observe the result in the Output window. (Figure-1.23 below)
AAAAAAAAAABBBBBBBBBBCCCCCCCCCC |
Figure-1.23: Result of running ExtendThreadClassTest2 application
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javathreads/samples/ExtendThreadClassTest2. You can just open it and run it.
5. For your own exercise, modify ExtendThreadClassTest2.java as following. Build and run the application.
- Create and start another thread.
- Set the name of the thread as “MyOwn”
Summary
Exercise 2: Implement Runnable interface
- Create and start a thread by implementing Runnable interface – start() method is not in the constructor
- Create and start a thread by implementing Runnable interface – start() method is in the constructor
(2.1) Create and start a thread by implementing Runnable interface – start() method is not in the constructor
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in RunnableThreadTest1 as project name.
- For Create Main Class field, type in RunnableThreadTest1.
- Click Finish.
- Observe that RunnableThreadTest1 project appears and IDE generated RunnableThreadTest1.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated RunnableThreadTest1.java as shown in Code-2.11 below. Study the code by paying special attention to the bold fonted parts. Note that the start() method needs to be invoked explicitly after an object instance of the PrintNameRunnable class is created.
public class RunnableThreadTest1 {
public static void main(String args[]) { PrintNameRunnable pnt1 = new PrintNameRunnable(“A”); PrintNameRunnable pnt2 = new PrintNameRunnable(“B”); PrintNameRunnable pnt3 = new PrintNameRunnable(“C”); } |
Code-2.11: RunnableThreadTest1.java
3. Write PrintNameRunnable.java as shown in Code-2.12 below.
// The class implements Runnable interface class PrintNameRunnable implements Runnable { String name; PrintNameRunnable(String name) { // Implementation of the run() defined in the |
Code-2.12: PrintNameRunnable.java
4. Build and run the project
- Right click RunnableThreadTest1 project and select Run.
- Observe the result in the Output window. (Figure-2.13 below)
ACBACBACBACBACABCABCABCABCABCB |
Figure-2.13: Result of running RunnableThreadTest1 application
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javathreads/samples/RunnableThreadTest1. You can just open it and run it.
5. For your own exercise, do the following. Build and run the application.
- Create another class called MyOwnRunnableClass that implements Runnable interface
- MyOwnRunnableClass displays values 1 to 10 inside its run() method
- Modify RunnableThreadTest1.java to start 2 thread instances of MyOwnRunnableClass.
(2.2) Create and start a thread by implementing Runnable interface – start() method is in the constructor
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in RunnableThreadTest2 as project name.
- For Create Main Class field, type in RunnableThreadTest2.
- Click Finish.
- Observe that RunnableThreadTest2 project appears and IDE generated RunnableThreadTest2.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated RunnableThreadTest2.java as shown in Code-2.21 below. Study the code by paying special attention to the bold fonted parts.
public class RunnableThreadTest2 {
public static void main(String args[]) { // Since the constructor of the PrintNameRunnable new PrintNameRunnable(“B”); |
Code-2.21: RunnableThreadTest2.java
3. Write PrintNameRunnable.java as shown in Code-2.22 below. Study the code by paying special attention to the bold fonted parts. Note that the start() method is in the constructor of the PrintNameRunnable class.
// The class implements Runnable interface class PrintNameRunnable implements Runnable { Thread thread; PrintNameRunnable(String name) { // Implementation of the run() defined in the |
Code-2.22: PrintNameRunnable.java
4. Build and run the project
- Right click RunnableThreadTest2 project and select Run.
- Observe the result in the Output window. (Figure-1.23 below)
ABCABCABCABCABCABCABCBACBACBAC |
Figure-2.23: Result of running RunnableThreadTest2 application
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javathreads/samples/RunnableThreadTest2. You can just open it and run it.
Summary
In this exercise, you have learned how to create a class that implements Runnable interface and starts a thread.
Exercise 3: ThreadsGroup, View all threads, ThreadPriority
(3.1) Display threads of a ThreadGroup
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in ThreadGroupTest as project name.
- For Create Main Class field, type in ThreadGroupTest.
- Click Finish.
- Observe that ThreadGroupTest project appears and IDE generated ThreadGroupTest.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated ThreadGroupTest.java as shown in Code-3.11 below. Study the code by paying special attention to the bold fonted parts.
public class ThreadGroupTest {
public static void main (String[] args) { // Start three threads first. They should belong // Get ThreadGroup of the current thread and display // Display the names of the threads in the current } |
Code-3.11: ThreadGroupTest.java
3. Write SimpleThread.java as shown in Code-3.12 below.
public class SimpleThread extends Thread {
public SimpleThread(String str) { public void run() { |
Code-3.12: SimpleThread.java
4. Build and run the project
- Right click ThreadGroupTest project and select Run.
- Observe the result in the Output window. (Figure-3.13 below)
Number of active threads in this thread group = 4 Thread main in thread group main Thread Boston in thread group main Thread New York in thread group main Thread Seoul in thread group main DONE! Seoul DONE! New York DONE! Boston |
Figure-3.13: Result of running ThreadGroupTest application
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javathreads/samples/ThreadGroupTest. You can just open it and run it.
5. For your own exercise, do the following. Build and run the application.
- Modify ThreadGroupTest.java to create another (4th) SimpleThread instance using your capital city of your country.
(3.2) Display all threads in the system
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in DisplayAllThreads as project name.
- For Create Main Class field, type in DisplayAllThreads.
- Click Finish.
- Observe that DisplayAllThreads project appears and IDE generated DisplayAllThreads.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated DisplayAllThreads.java as shown in Code-3.21 below. Study the code by paying special attention to the bold fonted parts.
public class DisplayAllThreads {
public static void main(String[] args) { // Start three threads first. They should belong Thread[] tarray = findAllThreads(); for (int i=0; i<tarray.length;i++){ } // Create an array of all threads in the system. ThreadGroup topGroup = group; while (group != null) { int estimatedSize = topGroup.activeCount() * 2; int actualSize = topGroup.enumerate(slackList); Thread[] list = new Thread[actualSize]; return list; |
Code-3.21: DisplayAllThreads.java
3. Write SimpleThread.java as shown in Code-3.22 below.
public class SimpleThread extends Thread {
public SimpleThread(String str) { public void run() { |
Code-3.22: SimpleThread.java
4. Build and run the project
- Right click DisplayAllThreads project and select Run.
- Observe the result in the Output window. (Figure-3.23 below)
Thread Reference Handler in thread group system Thread Finalizer in thread group system Thread Signal Dispatcher in thread group system Thread main in thread group main Thread Boston in thread group main Thread New York in thread group main Thread Seoul in thread group main DONE! New York DONE! Seoul DONE! Boston |
Figure-1.23: Result of running DisplayAllThreads application
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javathreads/samples/DisplayAllThreads. You can just open it and run it.
5. For your own exercise, do the following. Build and run the application.
- Modify DisplayAllThreads.java to create another (4th) SimpleThread instance using your capital city of your country.
(3.3) Set thread priority
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in ThreadsPriority as project name.
- For Create Main Class field, type in ThreadsPriority.
- Click Finish.
- Observe that ThreadsPriority project appears and IDE generated ThreadsPriority.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated ThreadsPriority.java as shown in Code-3.31 below. Study the code by paying special attention to the bold fonted parts.
public class ThreadsPriority {
public static void main(String[] args) { Thread t1 = new SimpleThread(“Boston”); Thread t2 = new SimpleThread(“New York”); Thread t3 = new SimpleThread(“Seoul”); } |
Code-3.31: ThreadsPriority.java
3. Write SimpleThread.java as shown in Code-3.32 below.
public class SimpleThread extends Thread {
public SimpleThread(String str) { public void run() { |
Code-3.32: SimpleThread.java
4. Build and run the project
- Right click ThreadsPriority project and select Run.
- Observe the result in the Output window. (Figure-3.33 below)
0 Boston Priority = 10 0 Seoul Priority = 1 0 New York Priority = 5 1 Boston Priority = 10 1 Seoul Priority = 1 1 New York Priority = 5 2 Boston Priority = 10 2 Seoul Priority = 1 3 Boston Priority = 10 2 New York Priority = 5 4 Boston Priority = 10 3 New York Priority = 5 5 Boston Priority = 10 6 Boston Priority = 10 7 Boston Priority = 10 8 Boston Priority = 10 9 Boston Priority = 10 Done! Boston 4 New York Priority = 5 5 New York Priority = 5 6 New York Priority = 5 7 New York Priority = 5 8 New York Priority = 5 9 New York Priority = 5 Done! New York 3 Seoul Priority = 1 4 Seoul Priority = 1 5 Seoul Priority = 1 6 Seoul Priority = 1 7 Seoul Priority = 1 8 Seoul Priority = 1 9 Seoul Priority = 1 Done! Seoul |
Figure-3.33: Result of running ThreadsPriority application
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javathreads/samples/ThreadsPriority. You can just open it and run it.
Summary
Exercise 4: Synchronization
(4.1) Build and run a program in which threads are NOT synchronized
1. Create a new NetBeans project
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in UnsynchronizedExample as project name.
- For Create Main Class field, type in UnsynchronizedExample.
- Click Finish.
- Observe that UnsynchronizedExample project appears and IDE generated UnsynchronizedExample.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated UnsynchronizedExample.java as shown in Code-4.11 below.
public class UnsynchronizedExample {
public static void main(String[] args) { } |
Code-4.11: UnsynchronizedExample.java
3. Write PrintStringsThread.java as shown in Code-4.12 below.
public class PrintStringsThread implements Runnable {
Thread thread; PrintStringsThread(String str1, String str2) { public void run() { } |
Code-4.12: PrintStringsThread.java
4. Write TwoStrings.java as shown in Code-4.13 below. Study the code by paying special attention to the bold fonted parts. Note that the print method is not synchronized.
public class TwoStrings {
// This method is not synchronized |
Code-4.13: TwoStrings.java
5. Build and run the project
- Right click UnsynchronizedExample project and select Run.
- Observe the result in the Output window. (Figure-4.14 below)
Hello How are Thank you there. very much! you? |
Figure-4.14: Result of running UnsynchronizedExample application
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javathreads/samples/UnsynchronizedExample. You can just open it and run it.
(4.2) Build and run a program in which threads are synchronized through synchronized method
1. Create a new NetBeans project
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in SynchronizedExample1 as project name.
- For Create Main Class field, type in SynchronizedExample1.
- Click Finish.
- Observe that SynchronizedExample1 project appears and IDE generated SynchronizedExample1.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated SynchronizedExample1.java as shown in Code-4.21 below.
public class SynchronizedExample1 {
public static void main(String[] args) { } |
Code-4.21: SynchronizedExample1.java
3. Write PrintStringsThread.java as shown in Code-4.22 below.
public class PrintStringsThread implements Runnable {
Thread thread; PrintStringsThread(String str1, String str2) { public void run() { } |
Code-4.22: PrintStringsThread.java
4. Write TwoStrings.java as shown in Code-4.23 below. Study the code by paying special attention to the bold fonted parts.
public class TwoStrings {
// This method is now synchronized |
Code-4.23: TwoStrings.java
5. Build and run the project
- Right click SynchronizedExample1 project and select Run.
- Observe the result in the Output window. (Figure-4.24 below)
How are you? Thank you very much! Hello there. |
Figure-4.24: Result of running UnSynchronizedExample1 application
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javathreads/samples/SynchronizedExample1. You can just open it and run it.
(4.3) Build and run a program in which threads are synchronized through synchronized statement on common object
1. Create a new NetBeans project
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in SynchronizedExample2 as project name.
- For Create Main Class field, type in SynchronizedExample2.
- Click Finish.
- Observe that SynchronizedExample2 project appears and IDE generated SynchronizedExample2.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated SynchronizedExample2.java as shown in Code-4.31 below.
public class SynchronizedExample2 {
public static void main(String[] args) { TwoStrings ts = new TwoStrings(); new PrintStringsThread(“Hello “, “there.”, ts); } |
Code-4.31: SynchronizedExample2.java
3. Write PrintStringsThread.java as shown in Code-4.32 below. Study the code by paying special attention to the bold fonted parts.
public class PrintStringsThread implements Runnable {
Thread thread; PrintStringsThread(String str1, String str2, public void run() { |
Code-4.32: PrintStringsThread.java
4. Write TwoStrings.java as shown in Code-4.33 below.
public class TwoStrings {
static void print(String str1, String str2) { |
Code-4.33: TwoStrings.java
5. Build and run the project
- Right click SynchronizedExample2 project and select Run.
- Observe the result in the Output window. (Figure-4.34 below)
How are you? Thank you very much! Hello there. |
Figure-4.34: Result of running UnSynchronizedExample2 application
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javathreads/samples/SynchronizedExample2. You can just open it and run it.
Summary
Exercise 5: Inter-thread communication
(5.1) Producer-Consumer without inter-thread communication
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in ProducerConsumerUnsynchronized as project name.
- For Create Main Class field, type in ProducerConsumerUnsynchronized.
- Click Finish.
- Observe that ProducerConsumerUnsynchronized project appears and IDE generated ProducerConsumerUnsynchronized.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated ProducerConsumerUnsynchronized.java as shown in Code-5.11 below.
public class ProducerConsumerUnsynchronized {
public static void main(String[] args) { CubbyHole c = new CubbyHole(); Producer p1 = new Producer(c, 1); p1.start(); |
Code-5.11: ProducerConsumerUnsynchronized.java
3. Write CubbyHole.java as shown in Code-5.12 below. Study the code by paying special attention to the bold fonted parts.
// Unsynchronized CubbyHole. // // Results are unpredictable; a number may be read before a number has // been produced or multiple numbers may be produced with only one or // two being read adding synchronization ensures that a number is first // produced, then read in the correct order. public class CubbyHole { public int get() { public void put(int value) { |
Code-5.12: CubbyHole.java
4. Write Producer.java as shown in Code-5.13 below.
public class Producer extends Thread { private CubbyHole cubbyhole; private int number; public Producer(CubbyHole c, int number) { public void run() { |
Code-5.13: Producer.java
5. Write Consumer.java as shown in Code-5.14 below.
public class Consumer extends Thread { private CubbyHole cubbyhole; private int number; public Consumer(CubbyHole c, int number) { public void run() { |
Code-5.14: Consumer.java
6. Build and run the project
- Right click ProducerConsumerUnsynchronized project and select Run.
- Observe the result in the Output window. (Figure-5.15 below)
Producer #1 put: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Consumer #1 got: 0 Producer #1 put: 1 Producer #1 put: 2 Producer #1 put: 3 Producer #1 put: 4 Producer #1 put: 5 Producer #1 put: 6 Producer #1 put: 7 Producer #1 put: 8 Producer #1 put: 9 |
Figure-5.15: Result of running ProducerConsumerUnsynchronized application
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javathreads/samples/ProducerConsumerUnsynchronized. You can just open it and run it.
(5.2) Producer-Consumer with inter-thread communication
1. Create a new NetBeans project
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in ProducerConsumerSynchronized as project name.
- For Create Main Class field, type in ProducerConsumerSynchronized.
- Click Finish.
- Observe that ProducerConsumerSynchronized project appears and IDE generated ProducerConsumerSynchronized.java is displayed in the source editor window of NetBeans IDE.
public class ProducerConsumerSynchronized {
public static void main(String[] args) { CubbyHole c = new CubbyHole(); Producer p1 = new Producer(c, 1); p1.start(); |
3. Write CubbyHole.java as shown in Code-5.22 below. Study the code by paying special attention to the bold fonted parts.
public class CubbyHole {
private int contents; public synchronized int get(int who) { public synchronized void put(int who, int value) { |
4. Write Producer.java as shown in Code-5.23 below.
public class Producer extends Thread {
private CubbyHole cubbyhole; public Producer(CubbyHole c, int number) { public void run() { |
5. Write Consumer.java as shown in Code-5.24 below.
public class Consumer extends Thread { private CubbyHole cubbyhole; private int number; public Consumer(CubbyHole c, int number) { public void run() { |
6. Build and run the project
- Right click ProducerConsumerSynchronized project and select Run.
- Observe the result in the Output window. (Figure-5.25 below)
Producer 1 put: 0 Consumer 1 got: 0 Producer 1 put: 1 Consumer 1 got: 1 Producer 1 put: 2 Consumer 1 got: 2 Producer 1 put: 3 Consumer 1 got: 3 Producer 1 put: 4 Consumer 1 got: 4 Producer 1 put: 5 Consumer 1 got: 5 Producer 1 put: 6 Consumer 1 got: 6 Producer 1 put: 7 Consumer 1 got: 7 Producer 1 put: 8 Consumer 1 got: 8 Producer 1 put: 9 Consumer 1 got: 9 |
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javathreads/samples/ProducerConsumerSynchronized. You can just open it and run it.
Summary
Exercise 6: Timer and TimerTask
(6.1) Schedule one-time task
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in TimerReminder as project name.
- For Create Main Class field, type in TimerReminder.
- Click Finish.
- Observe that TimerReminder project appears and IDE generated TimerReminder.java is displayed in the source editor window of NetBeans IDE.
2. Modify the IDE generated TimerReminder.java as shown in Code-6.11 below. Study the code by paying special attention to the bold fonted parts.
import java.util.Timer; import java.util.TimerTask; /** public class TimerReminder { Timer timer; public TimerReminder(int seconds) { class RemindTask extends TimerTask { public static void main(String args[]) { |
Code-6.11: TimerReminder.java
3. Build and run the project
- Right click TimerReminder project and select Run.
- Observe the result in the Output window. (Figure-6.12 below)
About to schedule Reminder task in 5 seconds Task scheduled. Time’s up! |
Figure-6.12: Result of running UnTimerReminder application
Solution: This exercise up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javathreads/samples/TimerReminder. You can just open it and run it.
(6.2) Schedule a repeating task
1. Create a new NetBeans project
- Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears.
- Under Choose Project pane, select Java under Categories and Java Application under Projects. Click Next.
- Under Name and Location pane, for the Project Name field, type in AnnoyingBeep as project name.
- For Create Main Class field, type in AnnoyingBeep.
- Click Finish.
- Observe that AnnoyingBeep project appears and IDE generated AnnoyingBeep.java is displayed in the source editor window of NetBeans IDE.
import java.util.Timer; import java.util.TimerTask; import java.awt.Toolkit; /** public class AnnoyingBeep { public AnnoyingBeep() { class RemindTask extends TimerTask { public void run() { public static void main(String args[]) { |
Code-6.21: AnnoyingBeep.java
- Right click AnnoyingBeep project and select Run.
- Observe the result in the Output window. (Figure-6.22 below)
About to schedule task. Task scheduled. Beep! Beep! Beep! Time’s up! |
Figure-6.22: Result
Summary
Homework exercise (for people who are taking Sang Shin’s “Java Programming online course”)
- Create a class called MyCurrentDate that implements Runnable interface.
- The MyCurrentDate class displays the current date and time 10 times, with 100 milli seconds interval – use sleep() method for this interval.
- Create a class called MyMain, which contans main() method, in which 3 instances of MyCurrentDate threads are being run.
- Zip file of the the MyRunnableProject NetBeans project. (Someone else should be able to open and run it as a NetBeans project.) You can use your favorite zip utility or you can use “jar” utility that comes with JDK as following.
- cd <parent directory that contains MyRunnableProject directory> (assuming you named your project as MyRunnableProject)
- jar cvf MyRunnableProject.zip MyRunnableProject (MyRunnableProject should contain nbproject directory)
- Captured output screen – name it as JavaIntro-javathreads.gif or JavaIntro-javathreads.jpg (or JavaIntro-javathreads.<whatver graphics format>)
- Any screen capture that shows that your program is working is good enough. No cosmetic polishment is required.
- If you decide to use different IDE other than NetBeans, the zip file should contain all the files that are needed for rebuilding the project.