such as
suspend()
and
resume()
, because theycan lock up your programs or damage objects. Asa result, you should not call them in your code.Consult the SDK documentation for workaroundsto those methods. I do not cover deprecatedmethods in this series.
Construct threads
Thread
has eight constructors. The simplest are:
•
Thread()
, which creates a
Thread
object with a default name
•
Thread(String name)
, which creates a
Thread
object with a name that the
name
argument specifies
The next simplest constructors are
Thread(Runnable target)
and
Thread(Runnable target,String name)
. Apart from the
Runnable
parameters, those constructors are identical to theaforementioned constructors. The difference: The
Runnable
parameters identify objects outside
Thread
that provide the
run()
methods. (You learn about
Runnable
later in this article.) Thefinal four constructors resemble
Thread(String name)
,
Thread(Runnable target)
, and
Thread(Runnable target, String name)
; however, the final constructors also include a
ThreadGroup
argument for organizational purposes.One of the final four constructors,
Thread(ThreadGroup group, Runnable target, Stringname, long stackSize)
, is interesting in that it lets you specify the desired size of the thread'smethod-call stack. Being able to specify that size proves helpful in programs with methods thatutilize recursion—an execution technique whereby a method repeatedly calls itself—to elegantlysolve certain problems. By explicitly setting the stack size, you can sometimes prevent
StackOverflowError
s. However, too large a size can result in
OutOfMemoryError
s. Also, Sunregards the method-call stack's size as platform-dependent. Depending on the platform, themethod-call stack's size might change. Therefore, think carefully about the ramifications to your program before writing code that calls
Thread(ThreadGroup group, Runnable target,String name, long stackSize)
.
Start your vehicles
Threads resemble vehicles: they move programs from start to finish.
Thread
and
Thread
subclass objects are not threads. Instead, they describe a thread's attributes, such as its name, andcontain code (via a
run()
method) that the thread executes. When the time comes for a newthread to execute
run()
, another thread calls the
Thread
's or its subclass object's
start()
method. For example, to start a second thread, the application's starting thread—which executes
main()
—calls
start()
. In response, the JVM's thread-handling code works with the platform toensure the thread properly initializes and calls a
Thread
's or its subclass object's
run()
method.
Leave a Comment