Android multithreaded Research (4)--from a question about a face

Source: Internet
Author: User

There is one such interview problem: Open a sub-thread and the main thread run at the same time, the child thread output 10 times and then the main thread output 100 times, so repeat 50 times. Let's look at the following code:

Package com.maso.test;/** * * @author Administrator * Two threads, which is a main thread, the first one runs output 10 times, the main process then runs output 100 times, so repeat 50 times */public class T HREADTEST3 implements runnable{private static test test, @Overridepublic void Run () {for (int i=0; i<50; i++) {test.f1 (i) ;}} public static void Main (string[] args) {test = new test (), New Thread (New ThreadTest3 ()). Start (); for (int i=0; i<50; i++) {TEST.F2 (i);}} /** * Control and logic and data classification (this class is data) * @author Administrator * */static class test{private Boolean isf1 = true;/** * Output 10 times */public s ynchronized void F1 (int j) {if (!ISF1) {try {this.wait ();} catch (Interruptedexception e) {e.printstacktrace ()}} for (int i=1; i<=10; i++) {System.out.println (Thread.CurrentThread (). GetName () + "first" + j + "Second round patrol, output" + i);} ISF1 = False;notify ();} /** * Output 100 times */public synchronized void F2 (int j) {if (ISF1) {try {this.wait ();} catch (Interruptedexception e) {E.printstack Trace ();}} for (int i=1; i<=100; i++) {System.out.println (Thread.CurrentThread (). GetName () + "first" + j + "Second round patrol, output" + i);} ISF1 = True;notifY ();}}} 
The above inference is using the IF statement, which does not seem to be a problem, in fact, it is not safe to do so, because the thread is waiting for the possibility of false wake, so we need to use the while statement. In addition, when using wait and notify, you need to pay attention to the following points:

1. When you call the Wait method and the Notity method of object, you must first obtain an object lock (which must be written in synchronized).

2. Assuming that the wait method for object is called, the thread has dropped the object lock.

3, assuming that A1, A2, A3 are all in object.wait (), then B call Object.notify () can only wake up A1, A2, A3 One (detailed which is determined by the JVM)

4, Object.notifyall () can wake up all.

5, B When waking A, B assumes that also holds the object lock, then waits until B releases the lock, A has the opportunity to run.

What's the difference between sleep and wait?

Sleep () does not release the object lock, and wait () releases the object lock. However, wait () and sleep () are able to break the thread's suspend state through the interrupt () method, causing the line Cheng Lima to throw interruptedexception. Assuming thread A wants to end thread B immediately, it is able to invoke the interrupt method on thread B, the corresponding threading instance. Assuming that thread B is wait/sleep/join at the moment, thread B will immediately throw interruptedexception, and return directly in catch () {} to safely end the thread. It is important to note that Interruptedexception is thrown from within the thread itself, not by the interrupt () method. When calling interrupt () on a thread, the thread will not throw interruptedexception at all if it is running normal code. However, once the thread enters wait ()/sleep ()/join (), it immediately throws the interruptedexception.

Let's look at the thread life cycle:


The methods for implementing thread scheduling are as follows:

1, Sleep (): The thread is to let the thread sleep for a certain time, need to capture interruptedexception

2, Yield (): suspend the current thread, let the same rank priority of the thread run, it is assumed that no hierarchy of priority threads will not work. When it works, it will let the CPU run and go into a ready state.

3. Join (): Let a thread wait until the thread that calls the Join method finishes running and then continues.


Look at the code:

public class ThreadTest4 implements runnable{private static int a = 0, @Overridepublic void Run () {for (int i=0; i<10; i+ +) {a++;}} public static void Main (string[] args) {new Thread (new ThreadTest4 ()). Start (); System.out.println (a);}}
Does this code output 10? The answer is no, because after the child thread is started, the value of a is immediately output, when the child thread has no action on a. Changes such as the following:

public class ThreadTest4 implements runnable{private static int a = 0, @Overridepublic void Run () {for (int i=0; i<10; i+ +) {a++;}} public static void Main (string[] args) throws Interruptedexception {thread t = new Thread (new ThreadTest4 ()); T.start (); T.J Oin (); System.out.println (a);}}
This output of the 10,join () method shows that it allows other threads to wait for the thread to run before it is finished.






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.