Threads in Java
Submitted by pavel7_7_7 on Monday, September 1, 2014 - 10:47.
Multithreading application are really powerful applications. These applications can solve multiple tasks in the same time. Java programming language offers a good and flexible mechanism for using threads in your programs.
There are two possibilities to create your own threads: the first way is to implement interface
So, to create a thread class you need to override the
The members of this class are:
We need to have a thread object in the class to start your own thread.
The constructor of the class is presented here:
Also, in this class there is a method, used to set the priority of the thread:
The second way of extending the
Now, you can add any feature you want. I did it in the simple way by adding a message to be shown in the constructor after calling the constructor of the super class:
The method run is defined similarly to the way I did it in the first case:
It shows a message with the interval of 300 milliseconds.
Now we can test both methods.
Let's create three thread object in the
Now we can set different priorities to the objects:
I wan't to show the priorities of all threads only after all the threads are terminated.That's why I'm using
Join method can throw
The output of this program will be different on different pc.
This is a simple tutorial about threads, but I hope, it can help you to understand more difficult thing. The whole eclipse project is attached, so you can review it.
Runnable
and the second way is to extend class Thread
.
I'll show you the both variants.
The interface Runnable
consists of one method:
- public abstract void run();
- }
run()
method.
I'll show you an example of a thread, that will show messages with a specified interval of time:
In the constructor
start()
method is called. This method calls the method run()
that must be overridden:
- @Override
- public void run() {
- // TODO Auto-generated method stub
- try{
- for (int i = 10; i > 0; --i){
- myThread.sleep(sleep_time);
- }
- }
- }
- }
- public void setPriority(int p){
- myThread.setPriority(p);
- }
Thread
class consist of defining additional properties to the base class:
- public void run(){
- try{
- for (int i = 10; i > 0; --i){
- }
- }
- }
- }
public static void main()
method:
- RunnableThread t1 = new RunnableThread("First",500);
- RunnableThread t2 = new RunnableThread("Second",100);
- ThreadExt t3 = new ThreadExt("Third");
- t1.setPriority(1);
- t1.setPriority(10);
- t3.setPriority(4);
join()
method to wait for thread termination in main thread:
- try{
- t1.myThread.join();
- t2.myThread.join();
- t3.join();
- }
- }
InterruptedException
if the main thread is interrupted. So a try/catch block is necessary here.
Now I can show the priority of all threads:
The output of this program is:
- Waiting for threads termination
- Priority of the first thread was 10
- Priority of the second thread was 5
- Priority of the third thread was 4
Add new comment
- 15 views