How do I pass a variable into a thread that can be accessed from the run() method?
Created May 4, 2012
Alex Chaffee Create a subclass of Thread with a custom instance variable and initialize it in the constructor. (This is basic object-oriented programming design, BTW.)
For instance, to pass in a PrintWriter from the doGet method of a Servlet:
public MyThread extends Thread { private PrintWriter myWriter; public MyThread(PrintWriter writer) { myWriter = writer; } public void run() { ... myWriter.print(...); ... } } public void doGet(...) { ... MyThread mt = new MyThread(response.getWriter()); mt.start(); mt.join(); ... }This is a very dangerous technique, however, since the doGet() method may return before the thread finishes. So watch out. That's why you need the join() call -- it waits until the thread is finished.