Java Reference
In-Depth Information
The
Producer
and
Consumer
classes inherit the
Thread
class. They override the
run()
method of the
Thread
class.
Both of them accept an object of the
Buffer
class in their constructors to use it in their
run()
method. The
Producer
class generates a random integer in its
run()
method inside an infinite loop and keeps writing it to the buffer. The
Consumer
class keeps consuming data from the buffer in an infinite loop.
The
ProducerConsumerTest
class creates all three objects (a buffer, a producer, and a consumer) and starts the
producer and consumer threads. Since both classes (
Producer
and
Consumer
) use infinite loops inside the
run()
method, you will have to terminate the program forcibly, such as by pressing
Ctrl + C
, if you are running this
program from a Windows command prompt.
Which Thread Is Executing?
The
Thread
class has some useful
static
methods; one of them is the method
currentThread()
. It returns the
reference of the
Thread
object that calls this method. Consider the following statement:
Thread t = Thread.currentThread();
The statement will assign the reference of the thread object that executes the above statement to the variable
t
.
Note that a statement in Java can be executed by different threads at different points in time during the execution of
a program. Therefore,
t
may be assigned the reference of a different
Thread
object when the statement is executed at
different times in the same program. Listing 6-10 demonstrates the use of the
currentThread()
method.
Listing 6-10.
Using the Thread.currentThread() Method
// CurrentThread.java
package com.jdojo.threads;
public class CurrentThread extends Thread {
public CurrentThread(String name) {
super(name);
}
@Override
public void run() {
Thread t = Thread.currentThread();
String threadName = t.getName();
System.out.println("Inside run() method: " + threadName);
}
public static void main(String[] args) {
CurrentThread ct1 = new CurrentThread("First Thread");
CurrentThread ct2 = new CurrentThread("Second Thread");
ct1.start();
ct2.start();
// Let's see which thread is executing the following statement
Thread t = Thread.currentThread();
String threadName = t.getName();
System.out.println("Inside main() method: " + threadName);
}
}