Example: Thread-specific data in a Java program
This example shows a Java™ program creating thread-specific data. Because a Java thread is created on an object, the use of thread-specific data is transparent.
Java is a language that performs garbage collection. Note the lack of data destructors or other cleanup action.
Note: By using
the code examples, you agree to the terms of the Code license and disclaimer information.
/*
FileName: ATEST22.java
The output of this example is as follows:
Entered the testcase
Create/start threads
Thread Thread-1: Entered
Thread Thread-1: foo(), threadSpecific data=0 2
Thread Thread-1: bar(), threadSpecific data=0 2
Wait for the threads to complete
Thread Thread-2: Entered
Thread Thread-2: foo(), threadSpecific data=1 4
Thread Thread-2: bar(), threadSpecific data=1 4
Testcase completed
*/
import java.lang.*;
public class ATEST22 {
public final static int NUMTHREADS = 2;
static class theThread extends Thread {
int threadSpecific1;
int threadSpecific2;
public theThread(int i, int i2) {
threadSpecific1 = i;
threadSpecific2 = i2;
}
public void run() {
System.out.print("Thread " + getName() +
": Entered\n");
foo();
return;
}
void foo() {
System.out.print("Thread " + getName() +
": foo(), threadSpecific data=" +
String.valueOf(threadSpecific1) + " " +
String.valueOf(threadSpecific2) + "\n");
bar();
}
void bar() {
System.out.print("Thread " + getName() +
": bar(), threadSpecific data=" +
String.valueOf(threadSpecific1) + " " +
String.valueOf(threadSpecific2) + "\n");
}
}
public static void main(String argv[]) {
System.out.print("Entered the testcase\n");
System.out.print("Create/start threads\n");
theThread threads[] = new theThread[NUMTHREADS];
for (int i=0; i <NUMTHREADS; ++i) {
threads[i] = new theThread(i, (i+1)*2);
threads[i].start();
}
System.out.print("Wait for the threads to complete\n");
for (int i=0; i <NUMTHREADS; ++i) {
try {
threads[i].join();
}
catch (InterruptedException e) {
System.out.print("Join interrupted\n");
}
}
System.out.print("Testcase completed\nj");
System.exit(0);
}
}