1.3. The interface Runnable:
Before discussing the Thread class, we will study the Runnable interface in package java.lang. The Runnable interface offers us a unique method, the run method whose signature is as follows: Our treatment should be in this method. He can not take any parameter and can not return value.
Code:
Signature of the run
Public void run ();
If we need parameters, we pass to the builder who will store it in instance variable. An accessor can be set up to retrieve a value at the end of treatment.
1.4. The Thread class:
The Thread class of the java.lang package is one that must necessarily be derived for a class, so that it can be considered as a Thread and therefore executable in parallel. This concrete class implements the Runnable interface. The code you want to see implemented during activation should be placed in the run () method seen previously.
The main constructors of the Thread class are:
Code:
Public Thread ();
Public Thread (Runnable runnable);
Starting a Thread must be done by the start () method.
Code:
ExThread t = new ExThread ();
t.start ();
A simple implementation of Thread.
Code:
Public class ExThread extends Thread {
Public void run () {
// Do something
}
}
Code:
Public class ExThread extends Thread {
private String s;
Public ExThread (String s) {
this. s = s;
}
Public void run () {
/ / Do something with s
}
}
1.5. A Thread Example:
In the first concrete example, we learn to write a simple thread to initialize and run. To demonstrate that the thread is active at the same time as the main class, it will make postings on the console.
Code:
Public class ExThread extends Thread {
Public void run {} {
long str = System.currentTimeMillis {};
/ / Loop until the lifetime of the Thread is <5 seconds
while{System.currentTimeMillis {} <{str + {1000 * 5}}} {
/ / Processing
System.out.println {"Displayed by the thread"};
try {
/ / Pause
Thread.sleep {500};
}
catch {InterruptedException ex} {}
}
}
}
Code:
Public class Main {
Public Main {} {
/ / Create an instance of Thread
ExThread thr = new ExThread {};
/ / Enable Thread
thr.Start {};
/ / While the thr is alive ...
while{Thread.isAlive {}} {
/ / Do processing ...
System.out.println {"Line displayed by the hand"};
try {
/ / And take a break
Thread.sleep {800};
}
catch {InterruptedException ex} {}
}
}
Public static void main {String[] Args} {
new Main {};
}
}
Bookmarks