Friday, June 17, 2011

Chapter 6: Determining the Current Thread

Sometimes, you need to find out what the current thread is. In the most common case, code that belongs to an arbitrary object may need to invoke a method of the thread class. In other circumstances, code within a thread object may want to see if the code is being executed by the thread represented by the object or by a completely different thread.

You can retrieve a reference to the current thread by calling the currentThread() method (a static method of the Thread class). Therefore, to see if code is being executed by an arbitrary thread (as opposed to the thread represented by the object), you can use this pattern:

public class MyThread extends Thread {
public void run( ) {
if (Thread.currentThread( ) != this)
throw new IllegalStateException(
"Run method called by incorrect thread");
//... more code logic ...
}
}

Similarly, within an arbitrary object, you can use the currentThread() method to obtain a reference to a current thread. This technique can be used by a Runnable object to see whether it has been interrupted:

public class MyRunnable implements Runnable {
public void run( ) {
while (!Thread.currentThread( ).isInterrupted( )) {
//... more code logic ...
}
}
}

In fact, the Thread class includes a static method interrupted() that returns the value of Thread.currentThread().isInterrupted(); it also clears the interrupted flag. You'll often see both uses within threaded programs.

Previous: Stopping a Thread

Next: The Synchronized Keyword

No comments:

Post a Comment

© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers