Current Topic: 3.1.1. Thread and Runnable Examples
You have a privilege to create a quiz (QnA) related to this subject and obtain creativity score...
Reminder: there are two ways of creating threads:
- Create a class that extends the Thread class
- Create a class that implements the Runnable interface and then create a Thread object by passing a Runnable object in the constructor.
We will use the Passport Renew scenario to demostrate both cases.
To better organize multiple threads it is possible to collect them into a group. The ThreadGroup class does exactly this. We will elaborate more on the ThreadGroup later.
In the example below we just provide a constructor that allows a thread to join a thread group.
And as soon as one constructor is provided by a developer, default constructor will not be created automatically by Java. If you plan using a default constructor, you need to provide it in the class as it is illustrated in this example.
package week6.threads;
//In this example we create MyThread by extending the Thread class
public class MyThread extends Thread {
// provide the constructor for joining the thread group
public MyThread(ThreadGroup group, String threadName) {
super(group, threadName);
}
// providing default constructor; we must do this because
// after one constructor was created, default constructor is not created automatically
public MyThread() {
super();
}
// Thread must have the run() method,
// which is the implementation of the Runnable interface
public void run() {
boolean passportArrived = false;
System.out.println("Renew the passport!");
for (; !passportArrived;) {
// periodically check the mailbox event
System.out.println("Check your mailbox");
// if arrived set passportArrived=true
// if not wait for some time before checking again
try {
Thread.sleep(2000); // this thread will sleep (do nothing) for 2 seconds
} catch (Exception e) {
// never happen
}
}
}
/**
* Test the class MyThread
* The thread will display the message in the Console every 2 seconds
* To stop the program - click on the red box in the Eclipse
* @param args
*/
public static void main(String args[]) {
// create a thread group
ThreadGroup group = new ThreadGroup("parent");
MyThread myThread = new MyThread(group, "threadSample");
myThread.start(); // call the run() method
// do something else!
}
}
// The following two classes create threads by implementing the Runnable interface
package its.day14.threads;
import java.util.Scanner;
/**
* This thread periodically calls the checkMailbox() method till a user answer is yes
*/
public class MyRunnableMailbox implements Runnable {
private boolean passportArrived = false;
private Scanner sc = new Scanner(System.in);
public void run() {
System.out.println("Renew your passport!");
for (; !passportArrived;) {
// periodically check the mailbox event
// if arrived (the answer is yes) set passportArrived=true
checkPassportArrived();
// if not wait for some time before checking again
try {
Thread.sleep(9000); // this thread will sleep (do nothing) for 9 seconds
} catch (Exception e) {
// never happen
}
}
}
/**
* Use Scanner to get an answer from a user
*/
public void checkPassportArrived() {
System.out.println("Did your passport arrive?");
String answer = sc.nextLine();
if (answer.toLowerCase().startsWith("y")) {
passportArrived = true; // this will stop running
}
}
/**
* Test the thread
* @param args
*/
public static void main(String args[]) {
// create a runnable object first
MyRunnableMailbox myRunnableMailbox = new MyRunnableMailbox();
// then create a thread based on this runnable object
Thread mailboxThread = new Thread(myRunnableMailbox);
mailboxThread.start(); // call the run() method
// do something else!
}
}
package its.day14.threads;
import java.util.Scanner;
//This example illustrates the method of creating threads with the Runnable interface
/**
* This thread periodically calls the calculate() method till the number becomes 40
*/
public class MyRunnableCalculator implements Runnable {
private int number = 0;
private int maxNumber = 40;
public void run() {
System.out.println("Renew the passport!");
for (; number < maxNumber;) {
// periodically check the mailbox event
// if arrived set passportArrived=true
calculate();
// if not wait for some time before checking again
try {
Thread.sleep(3000); // this thread will sleep (do nothing) for 3 seconds
} catch (Exception e) {
// never happen
}
}
}
public void calculate() {
number = number + 4;
System.out.println("The number is "+number);
System.out.println("Do not forget to check your mailbox!");
}
/**
* Test by running two threads: mailbox and calculator
* @param args
*/
public static void main(String args[]) {
// create a runnable object first
MyRunnableCalculator myRunnableCalculator = new MyRunnableCalculator();
// then create a thread based on this runnable object
Thread calculatorThread = new Thread(myRunnableCalculator);
calculatorThread.start(); // call the run() method
// do something else: check mailbox and click on the Console to answer the question
MyRunnableMailbox myRunnableMailbox = new MyRunnableMailbox();
// then create a thread based on this runnable object
Thread mailboxThread = new Thread(myRunnableMailbox);
mailboxThread.start(); // call the run() method
}
}
Was it clear so far?
Assignments: 1. Open Eclipse and create a new project: week6.threads.
2. Open this project and under the src create a new package its.day14.threads.
3. Right mouse click on the package name and create a new class MyThread.
4. Type into Eclipse the content of the class MyThread provided above. Please avoid copy/paste and still continue typing sources. This gives you comparable experience with the programmers who typed thousands of them from scratch.
Right mouse click on the source page and Run – As Java Application. The thread will display the message in the Console every 2 seconds. To stop the program - click on the red box in the Eclipse
5. Do similar things for MyRunnableMailbox and MyRunnableCalculator. Create a class by typing in Eclipse and Run – As Java Application. The test for MyRunnableCalculator will be running two threads: mailbox and calculator, this is a bit more fun, but the next one – SimpleGame - will be even better.
<br/>package week6.threads;
<br/>
<br/>//In this example we create MyThread by extending the Thread class
<br/>public class MyThread extends Thread {
<br/> // provide the constructor for joining the thread group
<br/> public MyThread(ThreadGroup group, String threadName) {
<br/> super(group, threadName);
<br/> }
<br/> // providing default constructor; we must do this because
<br/> // after one constructor was created, default constructor is not created automatically
<br/> public MyThread() {
<br/> super();
<br/> }
<br/> // Thread must have the run() method,
<br/> // which is the implementation of the Runnable interface
<br/> public void run() {
<br/> boolean passportArrived = false;
<br/> System.out.println("Renew the passport!");
<br/> for (; !passportArrived;) {
<br/> // periodically check the mailbox event
<br/> System.out.println("Check your mailbox");
<br/> // if arrived set passportArrived=true
<br/> // if not wait for some time before checking again
<br/> try {
<br/> Thread.sleep(2000); // this thread will sleep (do nothing) for 2 seconds
<br/> } catch (Exception e) {
<br/> // never happen
<br/> }
<br/>
<br/> }
<br/> }
<br/> /**
<br/> * Test the class MyThread
<br/> * The thread will display the message in the Console every 2 seconds
<br/> * To stop the program - click on the red box in the Eclipse
<br/> * @param args
<br/> */
<br/> public static void main(String args[]) {
<br/> // create a thread group
<br/> ThreadGroup group = new ThreadGroup("parent");
<br/> MyThread myThread = new MyThread(group, "threadSample");
<br/> myThread.start(); // call the run() method
<br/> // do something else!
<br/> }
<br/>
<br/>}
<br/><hr>
<br/>// The following two classes create threads by implementing the Runnable interface
<br/>
<br/>package its.day14.threads;
<br/>
<br/>import java.util.Scanner;
<br/>
<br/>/**
<br/> * This thread periodically calls the checkMailbox() method till a user answer is yes
<br/> */
<br/>public class MyRunnableMailbox implements Runnable {
<br/> private boolean passportArrived = false;
<br/> private Scanner sc = new Scanner(System.in);
<br/>
<br/> public void run() {
<br/> System.out.println("Renew your passport!");
<br/> for (; !passportArrived;) {
<br/> // periodically check the mailbox event
<br/> // if arrived (the answer is yes) set passportArrived=true
<br/> checkPassportArrived();
<br/> // if not wait for some time before checking again
<br/> try {
<br/> Thread.sleep(9000); // this thread will sleep (do nothing) for 9 seconds
<br/> } catch (Exception e) {
<br/> // never happen
<br/> }
<br/> }
<br/>
<br/> }
<br/> /**
<br/> * Use Scanner to get an answer from a user
<br/> */
<br/> public void checkPassportArrived() {
<br/> System.out.println("Did your passport arrive?");
<br/> String answer = sc.nextLine();
<br/> if (answer.toLowerCase().startsWith("y")) {
<br/> passportArrived = true; // this will stop running
<br/> }
<br/> }
<br/> /**
<br/> * Test the thread
<br/> * @param args
<br/> */
<br/> public static void main(String args[]) {
<br/> // create a runnable object first
<br/> MyRunnableMailbox myRunnableMailbox = new MyRunnableMailbox();
<br/> // then create a thread based on this runnable object
<br/> Thread mailboxThread = new Thread(myRunnableMailbox);
<br/> mailboxThread.start(); // call the run() method
<br/> // do something else!
<br/> }
<br/>}
<br/><hr>
<br/>package its.day14.threads;
<br/>
<br/>import java.util.Scanner;
<br/>
<br/>//This example illustrates the method of creating threads with the Runnable interface
<br/>/**
<br/> * This thread periodically calls the calculate() method till the number becomes 40
<br/> */
<br/>public class MyRunnableCalculator implements Runnable {
<br/> private int number = 0;
<br/> private int maxNumber = 40;
<br/> public void run() {
<br/> System.out.println("Renew the passport!");
<br/> for (; number < maxNumber;) {
<br/> // periodically check the mailbox event
<br/> // if arrived set passportArrived=true
<br/> calculate();
<br/> // if not wait for some time before checking again
<br/> try {
<br/> Thread.sleep(3000); // this thread will sleep (do nothing) for 3 seconds
<br/> } catch (Exception e) {
<br/> // never happen
<br/> }
<br/> }
<br/>
<br/> }
<br/>
<br/> public void calculate() {
<br/> number = number + 4;
<br/> System.out.println("The number is "+number);
<br/> System.out.println("Do not forget to check your mailbox!");
<br/> }
<br/> /**
<br/> * Test by running two threads: mailbox and calculator
<br/> * @param args
<br/> */
<br/> public static void main(String args[]) {
<br/> // create a runnable object first
<br/> MyRunnableCalculator myRunnableCalculator = new MyRunnableCalculator();
<br/> // then create a thread based on this runnable object
<br/> Thread calculatorThread = new Thread(myRunnableCalculator);
<br/> calculatorThread.start(); // call the run() method
<br/> // do something else: check mailbox and click on the Console to answer the question
<br/> MyRunnableMailbox myRunnableMailbox = new MyRunnableMailbox();
<br/> // then create a thread based on this runnable object
<br/> Thread mailboxThread = new Thread(myRunnableMailbox);
<br/> mailboxThread.start(); // call the run() method
<br/> }
<br/>}
<br/>
<br/>
Was it clear so far?
onclick="window.location.href='/BASE/jsp/demo.jsp?checkFlavor=itsp&issueID=63&intro=general&group=aitu&ur=f'">
Assignments: 1. Open Eclipse and create a new project: week6.threads.
2. Open this project and under the src create a new package its.day14.threads.
3. Right mouse click on the package name and create a new class MyThread.
4. Type into Eclipse the content of the class MyThread provided above. Please avoid copy/paste and still continue typing sources. This gives you comparable experience with the programmers who typed thousands of them from scratch.
Right mouse click on the source page and Run – As Java Application. The thread will display the message in the Console every 2 seconds. To stop the program - click on the red box in the Eclipse
5. Do similar things for MyRunnableMailbox and MyRunnableCalculator. Create a class by typing in Eclipse and Run – As Java Application. The test for MyRunnableCalculator will be running two threads: mailbox and calculator, this is a bit more fun, but the next one – SimpleGame - will be even better.