20.20
java.lang.Thread
THE PACKAGE JAVA.LANG
When a Java Virtual Machine starts up, there is usually a single non daemon
thread, which typically begins by invoking the method
main
of some designated
class. The Java Virtual Machine continues to execute threads according to the
thread execution model until all threads that are not daemon threads have stopped.
There are two ways to create a new thread of execution. One is to declare
some class to be a subclass of
Thread
; this subclass should override the
run
method of class
Thread
. An instance of the subclass can then be created and
started. For example, consider code for a thread whose job is to compute primes
larger than a stated value:
class PrimeThread extends Thread {
long minPrime;
PrimeThread(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
//
compute primes larger than
minPrime
...
}
}
The following code would then create a thread and start it running:
PrimeThread p = new PrimeThread(143);
p.start();
The other way to create a thread is to is to declare some class to implement the
Runnable
interface, which also requires that the class implement the
run
method.
An instance of the class can then be created, used to create a
Thread
, and started.
The same example in this other style looks like this:
class PrimeRun implements Runnable {
long minPrime;
PrimeRun(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
//
compute primes larger than
minPrime
...
}
}
The following code would then create a thread and start it running:
590
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved