Java Thread - Commonly Used Methods - java.lang.Thread Class

1. currentThread() – java.lang.Thread

 The java.lang.Thread.currentThread() method returns a reference to the currently executing thread object

EXAMPLE

public class ThreaTest {
	public static void attack() {
		System.out.println("Fight");
		System.out.println("Current Thread is: " + Thread.currentThread().getName());
	}

	public static void main(String[] args) throws InterruptedException {
		Thread t = new Thread() {
			@Override
			public void run() {
				attack();
			}
		}
		System.out.println("current main thread is: " + Thread.currentThread().getName());
		t.start();
	}
}

OUTPUT

current main thread is: main
Fight
Current Thread is: Thread-0

2. join() – java.lang.Thread

public final void join() throws InterruptedException
 Waits for this thread to die. An invocation of this method behaves in exactly the same way as the invocation join(0).
Throws: InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

3. join(long millis) – java.lang.Thread

public final void join(long millis) throws InterruptedException
 Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.
 This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.

Tips:

 Join method actually determines the exection of threads. When a thread calls Thread.join(), then this method will grad the CPU resource. This Method can be used in the following case.
 There is a sub-thread that costs long time. Then we can let that thread call subthread.join() thead to grab the CPU resource from the main thread. This guarantees that this sub-thread will return the result to the main thread before the main thread terminates. Or else our main thread may finish before the sub-thread, say it may not receive the result from sub-thread.

3. sleep(long millis) – java.lang.Thread

public static void sleep(long millis) throws InterruptedException
 Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

Tips:

 When a thread calls Thread.sleep(), it will not occupy the CPU resource, but it won't release the lock resource it grabs.

4. start() – java.lang.Thread

public void start()
 Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
 The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
 It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

5. yield() – java.lang.Thread

public static void yield()
 A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.
 Yield is a heuristic attempt to improve relative progression between threads that would otherwise over-utilise a CPU. Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect.
 It is rarely appropriate to use this method. It may be useful for debugging or testing purposes, where it may help to reproduce bugs due to race conditions. It may also be useful when designing concurrency control constructs such as the ones in the java.util.concurrent.locks package.

Tips:

 When a thread calls this method, it tells the scheduler that I am willing to degrade my priority, I can transfer from RUNNING state to RUNNABLE state.

6. interrupt() – java.lang.Thread

public void interrupt()
 Interrupts this thread.
 Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.
 If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
 If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread’s interrupt status will be set, and the thread will receive a ClosedByInterruptException.
 If this thread is blocked in a Selector then the thread’s interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector’s wakeup method were invoked.
 If none of the previous conditions hold then this thread’s interrupt status will be set.
 Interrupting a thread that is not alive need not have any effect.

Tips:

 Thread.interrupt() sets the interrupted status/flag of the target thread. Then code running in that target thread MAY poll the interrupted status and handle it appropriately.
 It is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.
 Some methods that block such as Object.wait() may consume the interrupted status immediately and throw an appropriate exception (usually InterruptedException)

   Reprint policy


《Java Thread - Commonly Used Methods - java.lang.Thread Class》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC