In 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
LESSONSEVENTEEN.JAVA
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 getTime.start(); new Thread(getMail).start(); new Thread(getMailAgain).start(); } }
GETTIME20.JAVA
// 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 // styles DEFAULT, SHORT, MEDIUM, LONG, or FULL // 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); System.out.println(timeOutput); System.out.println(dateOutput); System.out.println(); // You must wrap the sleep method in error handling // code to catch the InterruptedException exception // sleep pauses thread execution for 2 seconds below try { Thread.sleep(2000); } catch(InterruptedException e) {} } } }
GETTHEMAIL.JAVA
// 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(){ try { // 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"); } }
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???
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
thank you for response, i also want to know for web applications, if you know anything about this, please let me know, where should i look for this??
Thank you..
I will cover developing web applications with Java very soon.
okie, thank you very much…
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!!!.
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
Thanks for reply!!
If possible then make video tutorial about java.io(Input/Output) 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!!!!
I’ll be covering that later in the current tutorial. Don’t worry I’ll get there soon
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 ^_^
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?
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 LessonSeventeen.java?
I noticed on your tut that you have 3 separate “files”
Thanks
Save them as 3 separate files. Then execute LessonSeventeen which contains the main function. If you save them in the same directory they’ll find each other
Damn it! Got error because I typed starTime XD
Have to be really careful..
THANK YOU FOR ALWAYS RESPONDING! 🙂
Keep at it and you’ll get it. Little errors are part of the learning process. I respond to every comment, but some times it takes a little time 🙂
I know.. Should’ve seen your site/YT tut 2 mos ago.. now I only have 1 week to prepare.. Good Luck to me! XD Thanks again.. 🙂
Good luck! If you just need to understand the core java language, I cover it completely. I hope I can help 🙂
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.
i guess its threadname, priority,but does not get it why main is displayed , plz make it clear
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
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.
Robinson
Yes you have it. Thank you very much for the nice compliments. I do my best
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)
at GetTime20.run(GetTime20.java:63)
Can you please let me know the reason for this exception?
Thanks in advance
Please check the code I provide on my site. There is probably a little typo some place. I’m sure the code on my site works
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 GetTime20.java and defined everything in there for somehow its not connecting with file LessonSeventeen.java
Do you have both classes in the same folder? Are you using Eclipse like I am?
Hello Derek, I have a question,how can I see Runnable interface?
I’m not sure what you mean?
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.
Thank you for all the very nice compliments 🙂 I’m very happy that you enjoy my site