Java Video Tutorial 17

Java ThreadsIn this Java Video Tutorial I cover how to use Java threads.

A thread is just a block of code that is expected to execute while other blocks of code execute. That’s it. When you want to execute more than one block of code at a time you have to alert Java.

In this video I show you how to alert the interpreter. Part 1 of this series is here Java Video Tutorial. Heavily commented code follows the video.

If you like videos like this share it

The country codes I mentioned are here Country Codes

Code From the Video


public class LessonSeventeen{
	public static void main(String[] args){
		// Create a new Thread that executes the code in GetTime20
		Thread getTime = new GetTime20();
		// Create a new Thread created using the Runnable interface
		// Execute the code in run after 10 seconds
		Runnable getMail = new GetTheMail(10);
		Runnable getMailAgain = new GetTheMail(20);
		// Call for the code in the method run to execute
		new Thread(getMail).start();
		new Thread(getMailAgain).start();


// By using threads you can execute multiple blocks
// of code at the same time. This program will output 
// the current time and then at a specific time execute
// other code without stopping the time output

// Need this for Date and Locale classes
import java.util.*;

// Need this to format the dates
import java.text.DateFormat;

// By extending the Thread class you can run your code
// concurrently with other threads
public class GetTime20 extends Thread{
	// All of the code that the thread executes must be 
	// in the run method, or be in a method called for
	// from inside of the run method
	public void run(){
		// Creating fields that will contain date info
		Date rightNow;
		Locale currentLocale;
		DateFormat timeFormatter;
		DateFormat dateFormatter;
		String timeOutput;
		String dateOutput;
		// Output the current date and time 20 times
		for(int i = 1; i <= 20; i++){
			// A Date object contains date and time data
			rightNow = new Date();
			// Locale defines time formats depending on location
			currentLocale = new Locale("en", "US");
			// DateFormat allows you to define dates / times using predefined
			// getTimeInstance only outputs time information
			timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, currentLocale);
			// getDateInstance only outputs time information
			dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, currentLocale);
			// Convert the time and date into Strings
			timeOutput = timeFormatter.format(rightNow);
			dateOutput = dateFormatter.format(rightNow);
			// You must wrap the sleep method in error handling
			// code to catch the InterruptedException exception
			// sleep pauses thread execution for 2 seconds below
			try {
			catch(InterruptedException e)


// You can use the Runnable interface instead of
// wasting your 1 class extension.

public class GetTheMail implements Runnable {
	// Stores the number of seconds before the code
	// will be executed
	private int startTime;
	// Constructor that sets the wait time for each 
	// new Thread
	public GetTheMail(int startTime){
		this.startTime = startTime;
	// All of the code that the thread executes must be 
	// in the run method, or be in a method called for
	// from inside of the run method
	public void run(){
			// Don't execute until 10 seconds has passed if 
			// startTime equals 10
			Thread.sleep(startTime * 1000);
		catch(InterruptedException e)
		System.out.println("Checking for Mail");

30 Responses to “Java Video Tutorial 17”

  1. punit says:

    Hey nice video, but i have a question, although localization is used to change the entire webpage into country specific language, but what i have to do, if i want to convert the entire webpage into state/city specific language (ie. hindi, marathi), how can i do this???

    • admin says:

      I’ll get into language specific translation when I start making JavaServer pages. This is basically for stand alone applications instead of web applications. I’ll do my best to explain that topic, but I’m not very well versed in other speaking languages

  2. Parth says:

    Hey! I like your java tutorials. I think your regex tutorial is best.

    I want to know which IDE you use because I use notepad++ & in notepad++ console window is not at the right side.

    And, which screen recording software you use for making these tuts because it’s just awesome!!!.

    • admin says:

      I use Eclipse because it is free and looks exactly the same on every OS. A definite plus if you are making video tutorials for the world.

      I record my screencasts with Quicktime Player and edit them with iMovie. I used to think that Quicktime Player was the best, but since the last update it is kind of broken. I plan on purchasing a new screencasting program but haven’t decided which one yet.

      Thanks for stopping by

  3. Parth says:

    Thanks for reply!!

    If possible then make video tutorial about or about file. I want to completely understand which class used for what because there is streamreader & bufferedreader & char stream and Scanner etc.It is a bit confusing!!!!

  4. sara says:

    hi 🙂
    ur tutorials are amazing . i feel very thankful about what u do .

    i have a questions if u dont mind
    1. i am learning java to be able to bild app for android , so if i master the 60 lessons that u have made , do u think it’s enough to start learn android programing ??

    2. on this lesson is the” runnable” interface is built already in java ?? and what ist exactly

    thanks in advance ^_^

    • admin says:

      Thank you very much 🙂 Yes, if you understand Java you will understand how to make Android apps. I’m going to create a 6 month long Android tutorial in which I’ll cover everything. I’ll make very specific apps. You can expect it to be about 90 videos in length (15 minutes each) based on my estimates. It will be the largest, most in depth Android tutorial ever made.

      Runnable is just like any other interface in which it is a blueprint detailing what methods you need to use. Runnable works by instantiating a Thread instance and then passing itself in using a reference to code that needs to run on its own separate from other threads that are currently running. It is just like how you multitask. You can listen to music while you type an email. The code just executes in tandem.

      Does that make sense?

  5. Kim says:

    Hi… I’m confused as to how I’m going to do this.
    I am using notepad, since it is what’s required to us.
    Am i supposed to just put everything into 1 file and save it as

    I noticed on your tut that you have 3 separate “files”


  6. Aamir says:

    Thanks again sir for this video, actually i was working on some examples after watching this video and i am stuck here:

    NewThread() {
    // Create a new, second thread
    t = new Thread(this, “Demo Thread”);
    System.out.println(“Child thread: ” + t);
    t.start(); // Start the thread

    it is actually a part a of program and it produces an output of
    Child thread: Thread[Demo Thread,5,main]
    on its first line, i actually understood the program but i did not understand this output. what does Thread,these[],5 mean in it , plz clearify.

  7. Aamir says:

    i guess its threadname, priority,but does not get it why main is displayed , plz make it clear

    • Derek Banas says:

      main is a thread just like any other. A thread is just a series of statements that execute. Since main is just a series of statements as well it is a thread. I hope that makes sense

  8. Robinson says:

    Let’s see if I have understood…

    Runnable(interface) have all the methods that I need to creat a Thread(class)… So if a class A implements Runnable, I have everything that I need to create a Thread, using A as parameter for the Thread constructor? Does it make sense? (I like when you say “I hope that makes sense”)

    Congratulations, your work is great.

    Sorry my english, it is not that good.


  9. Akshay says:

    I am getting the following error after running the above code in eclipse :

    Exception in thread “Thread-0” java.lang.IllegalArgumentException: Cannot format given Object as a Date
    at java.text.DateFormat.format(Unknown Source)
    at java.text.Format.format(Unknown Source)

    Can you please let me know the reason for this exception?

    Thanks in advance

  10. Zohaib says:

    Hello Derek I’m trying to excute this exact same code but getting an error in LessonSeventeen Class Thread getTime = GetTime20(); is undefined for the type LessonSeventeen.
    I have created and defined everything in there for somehow its not connecting with file

  11. Tiny Tony says:

    You’re really a great teacher. Not only are the videos amazing but after coming to your website and seeing the code published with comments — it’s priceless. Thank you for sharing your knowledge and teaching us. I had you on YouTube as a subscriber for a very long time. I am super happy to have found this website and the rest of Derek Banas’ amazing tutorials. Thank you — truly for every minute, hour, day, you spend to do this for the rest of the world. This is my new domain.

Leave a Reply

Your email address will not be published.