A preliminary study of Java multithreading--yield () method and join () method __java

Source: Internet
Author: User
Tags thread class
one, threads and processes1, the process is a program (task) execution process, holding resources (shared memory, shared files) and threads, the process is dynamic, if the program is not implemented is not a process.
2, the thread is the smallest unit of execution in the system, there are multiple threads in the same process, threads share the resources of the process

There are two ways to create out-of-the-box Methods in Java: (1) inherit the thread class, rewrite the Run () method, (2) Implement the Runnable interface, and rewrite the Run () method.
second, yield () method

In the JDK documentation, the yield () method describes: pauses the currently executing thread object and executes other threads. In the case of multithreading, the CPU decides which thread to execute, and the yield () method is to suspend the current thread, giving it to other threads (including itself) to execute, and who performs the decision by the CPU. yield () method instance

Yieldrunnable.java

public class Yieldrunnable implements runnable{public
	volatile Boolean isrunning = true;
	
	@Override public
	Void Run () {
		String name = Thread.CurrentThread (). GetName ();
		SYSTEM.OUT.PRINTLN (name +) begins execution. ");
		
		while (isrunning) {
			for (int i = 1; i < 6; i++) {
				System.out.println (name +) executes ["+ i +] times");
				Note that yield is a static method
				Thread.yield ()
			;
		}
		
		SYSTEM.OUT.PRINTLN (name +) execution is complete. ");
	}
}
The main function that was executed

	public static void Main (string[] args) {
		yieldrunnable runnable1 = new yieldrunnable ();
		Yieldrunnable runnable2 = new yieldrunnable ();
		Thread thread1 = new Thread (runnable1, "Thread 1");
		Thread thread2 = new Thread (runnable2, "Thread 2"); 
		
		System.out.println ("Two threads ready to start Execution");
		Thread1.start ();
		Thread2.start ();
		
		try {
			thread.sleep;
		} catch (Interruptedexception e) {
			e.printstacktrace ();
		}
		
		Runnable1.isrunning = false;
		Runnable2.isrunning = false;
	}
Select partial execution result analysis:

1, the first situation:

......

Thread 1 has performed [1] times
Thread 2 has performed [1] times
Thread 2 has performed [2] times
Thread 2 has performed [3] times
Thread 2 has performed [4] times
Thread 1 has performed [2] times

......
As you can see from this execution, thread 1 has been executed once, give up executive power, the CPU will execute the power to the thread 2, thread 2 executed once after the execution power, but the CPU will still execute the power to 2, so that thread 2 repeatedly executed several times, the CPU is the execution of the right to thread 2, The CPU will not execute to thread 1 until the thread 2 has finished executing the 4th time.

2, the second situation:

......

Thread 1 has performed [1] times
Thread 2 has performed [3] times
Thread 1 has performed [2] times
Thread 2 has performed [4] times
Thread 1 has performed [3] times
Thread 2 has performed [5] times

......

From this execution result can be seen, thread 1 execution once, give up execution power, the CPU will execute power to thread 2, thread 2 executes once, the CPU will execute power to give 1 again, in this way several threads 1 and thread 2 are executed alternately.

From the above two execution results, after a thread executes the yield () method paused, the CPU decides which thread to execute next, can be another thread, or it can be the same thread.


The Join () method Join () method is the end of the thread that waits to invoke the join () method, and the program continues to execute, which applies to situations where an executing program must wait for the result of another thread's execution to continue to run. The Join () Method instance defines a thread: Joinrunnable.java

public class Joinrunnable implements Runnable {
	@Override public
	void Run () {
		String name = Thread.currentthr EAD (). GetName ();
		SYSTEM.OUT.PRINTLN (name +) begins execution. ");
		
		for (int i = 1; i < 6; i++) {
			System.out.println (name +) executes ["+ i +] times");}}

Let's take a look at a situation where the join () method is not used:
	public static void Main (string[] args) {
		joinrunnable runnable1 = new joinrunnable ();
		Thread thread1 = new Thread (runnable1, "Thread 1");

		System.out.println (the main thread begins execution.) ");
		Thread1.start ();

		System.out.println ("Main thread execution end.") ");
	}
Execution result: The main thread begins execution.
The main thread execution ends.
Thread 1 begins execution.
Thread 1 has performed [1] times
Thread 1 has performed [2] times
Thread 1 has performed [3] times
Thread 1 has performed [4] times
Thread 1 has performed [5] times

As you can see from the execution results, if you do not use the Join method, the thread that the main method is on (tentatively called the main thread) is finished before the joinrunnable thread (tentatively called the Child thread) is started, and no wait for the child thread to finish executing.
If you used the Join method:
	public static void Main (string[] args) {
		joinrunnable runnable1 = new joinrunnable ();
		Thread thread1 = new Thread (runnable1, "Thread 1");

		System.out.println (the main thread begins execution.) ");
		Thread1.start ();
		
		try {
			thread1.join ();
		} catch (Interruptedexception e) {
			e.printstacktrace ();
		}
		
		System.out.println ("Main thread execution end.") ");
	}
Execution result: The main thread begins execution.
Thread 1 begins execution.
Thread 1 has performed [1] times
Thread 1 has performed [2] times
Thread 1 has performed [3] times
Thread 1 has performed [4] times
Thread 1 has performed [5] times
The main thread execution ends.
As you can see from the execution result, the join () method is added, and after the main thread has started the child threads, the following actions continue after waiting for the child thread to finish executing.
Note: The join () method can only take effect after the start () method. You can refer to the following code to write the join () method before the start () method.
	public static void Main (string[] args) {
		joinrunnable runnable1 = new joinrunnable ();
		Thread thread1 = new Thread (runnable1, "Thread 1");

		System.out.println (the main thread begins execution.) ");
		try {
			thread1.join ();
		} catch (Interruptedexception e) {
			e.printstacktrace ();
		}
		Thread1.start ();

		System.out.println ("Main thread execution end.") ");
	}
Execution result: The main thread begins execution.
The main thread execution ends.
Thread 1 begins execution.
Thread 1 has performed [1] times
Thread 1 has performed [2] times
Thread 1 has performed [3] times
Thread 1 has performed [4] times
Thread 1 has performed [5] times
The join () method does not take effect, although the join () method is added, but is called before the start () method of the thread starts. Specific reasons can refer to the source code
 public final void join () throws Interruptedexception {join (0L); Public final synchronized void join (long L) throws interruptedexception {long L1 = System.curre
        Nttimemillis ();
        Long L2 = 0L;
        if (L < 0L) throw new IllegalArgumentException ("Timeout value is negative");
            if (L = = 0L) for (; IsAlive (); Waiting (0L));//isalive () is the state of the current thread, and wait (0) refers to waits until the thread is finished else do
                {if (!isalive ()) break;
                Long L3 = L-L2;
                if (L3 <= 0L) break;
                Wait (L3);
            L2 = System.currenttimemillis ()-L1;
    } while (true); }
From the source you can see that the join () method calls the join (long L) method, the value of the parameter L is 0, then in the judgement if the value of L is 0, then executes a loop, the loop executes the condition that the current thread is IsAlive (), or whether the thread is already running, If the thread does not start (that is, the Start method is not invoked), the loop condition is not valid and exits directly, meaning that the join () method does not take effect. Look at the source code here when found a small problem, for isAlive () and Wait () method of the object is a bit confusing, isAlive () to determine the current state of the thread, it is OK to understand, in the above example is referred to Thread1. But wait () method of the object is who, produced a doubt, according to the JDK's argument waiting should be the current thread, that is thread1, but the actual operation, waiting is the main thread, a bit of people do not touch the mind. Then I found this article online, which says that when we call the Wait () method of the lock object in the synchronized block, the calling thread blocks at the wait () statement until the other thread calls the thread's notify () method. The calling thread here refers to the main thread, because the Wai () method is called in the Synchronized method join (long L) in the thread class, so the main thread blocks until the thread executes and the Notify () method is invoked to continue execution, and this statement first records For future textual research.

Last little episode: Try to add something between the start () method and the join () method when coding, that is, call the Join () method when the start thread is invoked by calling the start () method to see if it appears: Start the child thread first, perform the related action, It then executes the contents of the main thread and waits for the child thread to finish execution. Sample code:
	public static void Main (string[] args) {
		joinrunnable runnable1 = new joinrunnable ();
		Thread thread1 = new Thread (runnable1, "Thread 1");

		System.out.println (the main thread begins execution.) ");
		Thread1.start ();
		The main thread sleeps 1 seconds after starting the child thread	
<span style= "White-space:pre" >		</span>try {
			thread.sleep (1000);
		} catch (Interruptedexception E1) {
			e1.printstacktrace ();
		}
		
		try {
			thread1.join ();
		} catch (Interruptedexception e) {
			e.printstacktrace ();
		}

		System.out.println ("Main thread execution end.") ");
	}
Execution result: The main thread begins execution.
Thread 1 begins execution.
Thread 1 has performed [1] times
Thread 1 has performed [2] times
Thread 1 has performed [3] times
Thread 1 has performed [4] times
Thread 1 has performed [5] times
The main thread execution ends.
The main thread hibernate 1 seconds is executed after the child thread execution ends. It can be inferred that, as long as the join () method is invoked after the start () method, no matter how much content is added between the two methods, the main thread waits for the child thread to finish execution before continuing.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.