Creating Threads in Java
Submitted by donbermoy on Sunday, June 15, 2014 - 18:19.
Today in Java, I'm going to teach you how to create a program that will create threads. We all know that a thread is a basic processing unit in our computer to which an operating system allocates processor time, and more than one thread can be executing code inside a process. The Java Virtual Machine (JVM) allows an application to have multiple threads of execution running concurrently. Thus, threads have priority. It is just like a racing program.
So, now let's start this tutorial!
1. Open JCreator or NetBeans and make a java program with a file name of thread.java.
2. Import java.io package. Hence we will use an input/output in accessing files, with IOException.
3. Provide a Thread extension in your classname and declare the following variables below.
4. Create a constructor named thread that is the same with the class name with the parameters of String carName, long delay. Make the delay variable equal to the aWhile variable that we have created above. Make the setDaemon equals to True. A daemon thread is also a thread, that does not prevent the Java Virtual Machine(JVM) from exiting when the program finishes but the thread is still running.
5. Create a method named run for running the thread when using the start keyword. This will display the carnames and have a delay in displaying it.
6. In your Main, create three threads that have the carnames and the delay parameters.
To stop our thread from running, put this Try and Catch statement below. The thread will stop if we press Enter.
Full source code:
Output:
Best Regards,
Engr. Lyndon Bermoy
IT Instructor/System Developer/Android Developer/Freelance Programmer
If you have some queries, feel free to contact the number or e-mail below.
Mobile: 09488225971
Landline: 826-9296
E-mail:[email protected]
Add and Follow me on Facebook: https://www.facebook.com/donzzsky
Visit and like my page on Facebook at: https://www.facebook.com/BermzISware
- import java.io.IOException;
- this.carName = carName;
- aWhile = delay;
- setDaemon(true);
- }
- public void run() {
- try {
- while (true) {
- sleep(aWhile);
- }
- }
- }
To start running threads, put this code below.
- first.start();
- second.start();
- third.start();
- try {
- }
- import java.io.IOException;
- private long aWhile;
- this.carName = carName;
- aWhile = delay;
- setDaemon(true);
- }
- public void run() {
- try {
- while (true) {
- sleep(aWhile);
- }
- }
- }
- first.start();
- second.start();
- third.start();
- try {
- }
- }
- }
Add new comment
- 20 views