Thread Access

Next, we’ll look into several methods that show us information about specific threads.

The Current Thread

First, we’ll examine the currentThread() method:

static Thread currentThread()

Gets the Thread object that represents the current thread of execution. The method is static and may be called through the Thread class name.

This is a static method of the Thread class, and it simply returns a Thread object that represents the current thread; the current thread is the thread that called the currentThread() method. The object returned is the same Thread object first created for the current thread.

But why is this method important? The Thread object for the current thread may not be saved anywhere, and even if it is, it may not be accessible to the called method. For example, let’s look at a class that performs socket I/O and stores the data it reads into an internal buffer. We’ll show the full implementation of this class in the next chapter, but for now, we’re interested only in its interface:

public class AsyncReadSocket extends Thread { StringBuffer result; public AsyncReadSocket(String host, int port) { // Open a socket to the given host. } public void run() { // Read data from a socket into the result string buffer. } // Get the string already read from the socket so far. // Only allows "Reader" threads to execute this method. public String getResult() { String reader = Thread.currentThread().getName(); if (reader.startsWith("Reader")) { String retval = result.toString(); ...

Get Java Threads, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.