Java Reference
In-Depth Information
value before being interrupted by the scheduler. Thread B now executes and reads the
same value.
Bothproblemscanbecorrectedbysynchronizingaccessto nextID sothatonlyone
thread can execute this method's code. All that is required is to add synchronized
to the method header prior to the method's return type; for example, static syn-
chronized int getNextID() .
Synchronization is also used to communicate between threads. For example, you
might design your own mechanism for stopping a thread (because you cannot use
Thread 's unsafe stop() methods for this task). Listing 4-24 shows how you might
accomplish this task.
Listing 4-24. Attempting to stop a thread
class ThreadStopping
{
public static void main(String[] args)
{
class StoppableThread extends Thread
{
private boolean stopped = false;
@Override
public void run()
{
while(!stopped)
System.out.println("running");
}
void stopThread()
{
stopped = true;
}
}
StoppableThread thd = new StoppableThread();
thd.start();
try
{
Thread.sleep(1000); // sleep for 1 second
}
Search WWH ::




Custom Search