Step by step _ Android development course [10] _ Thread learning, _ android_thread

Source: Internet
Author: User

Step by step _ Android development course [10] _ Thread learning, _ android_thread

Focus on technology, enjoy life! -- QQ: 804212028.
Link: http://blog.csdn.net/y18334702058/article/details/44624305

  • Topic: Thread Learning
    -When a program is started for the first time, Android starts a corresponding Main Thread at the same time. The Main Thread is mainly responsible for processing UI-related events, such as user key events, the user contacts screen events and Screen Drawing events, and distributes related events to corresponding components for processing. Therefore, the main thread is often called the UI thread.

Relationship between threads and processes:

A thread is an entity in a process. A process can have multiple threads. A thread must have a parent process.

There are two ways to create a thread:

1. Extend the java. lang. Thread class
Extend the java. lang. Thread class, that is, write the run () method to the Thread:

Import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. util. log; import android. widget. textView; public class MainActivity extends Activity {private TextView textView; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); textView = (TextView) findViewById (R. id. textView); new Thread (new Runnable () {@ Override public void run () {Message message = new Message (); message. what = 1; handler. sendMessage (message );}}). start ();} Handler handler = new Handler () {public void handleMessage (Message msg) {switch (msg. what) {case 1: textView. setText ("Doodle"); break;} super. handleMessage (msg );}};}

2. Implement the Runnable interface
Implement the Runnable interface for the class and separate the run method.

Import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. widget. textView; public class MainActivity extends Activity implements Runnable {private TextView textView; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); textView = (TextView) findViewById (R. id. textView); Thread thread = new Thread (); thread. start ();} Handler mHandler = new Handler () {public void handleMessage (Message msg) {switch (msg. what) {case 1: textView. setText ("Doodle"); break;} super. handleMessage (msg) ;}}; @ Override public void run () {// TODO Auto-generated method stub Message msg = new Message (); msg. what = 1; mHandler. sendMessage (msg );}}

Classic Thread ticket selling instance: (this gives us a better understanding of Thread usage)

Train tickets are sold in multiple windows. Assume that there are three window tickets at the same time, a total of 10 train tickets for sale. Start three threads to sell 10 tickets.

1. We open three threads to sell tickets:

public class CommonTestActivity extends Activity{    private Button mybutton;    private TextView mytext;    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        mybutton = (Button) findViewById(R.id.button);        mytext = (TextView) findViewById(R.id.text);        mybutton.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                // TODO Auto-generated method stub                MyThread myThread1 = new MyThread();                 MyThread myThread2= new MyThread();                 MyThread myThread3 = new MyThread();                 myThread1.start();                 myThread2.start();                 myThread3.start();             }        });    }    class MyThread extends Thread {        private int tickets = 10;        public void run() {            for (int i = 0; i < 200; i++) {                if (tickets > 0) {                    System.out.println(Thread.currentThread().getName() + "==>"                            + tickets--);                }            }        }    }}

Running result:

11-17 22:45:01. 234: I/System. out (672): Thread-10 ==> 10
11-17 22:45:01. 234: I/System. out (672): Thread-10 => 9
11-17 22:45:01. 234: I/System. out (672): Thread-10 ==> 8
11-17 22:45:01. 234: I/System. out (672): Thread-10 ==> 7
11-17 22:45:01. 234: I/System. out (672): Thread-10 ==> 6
11-17 22:45:01. 234: I/System. out (672): Thread-10 ==> 5
11-17 22:45:01. 234: I/System. out (672): Thread-10 ==> 4
11-17 22:45:01. 234: I/System. out (672): Thread-10 ==> 3
11-17 22:45:01. 244: I/System. out (672): Thread-10 ==> 2
11-17 22:45:01. 244: I/System. out (672): Thread-10 ==> 1
11-17 22:45:01. 244: I/System. out (672): Thread-11 => 10
11-17 22:45:01. 244: I/System. out (672): Thread-11 => 9
11-17 22:45:01. 244: I/System. out (672): Thread-11 => 8
11-17 22:45:01. 244: I/System. out (672): Thread-11 ==> 7
11-17 22:45:01. 244: I/System. out (672): Thread-11 => 6
11-17 22:45:01. 254: I/System. out (672): Thread-11 => 5
11-17 22:45:01. 254: I/System. out (672): Thread-11 => 4
11-17 22:45:01. 254: I/System. out (672): Thread-11 => 3
11-17 22:45:01. 254: I/System. out (672): Thread-11 => 2
11-17 22:45:01. 254: I/System. out (672): Thread-11 => 1
11-17 22:45:01. 264: I/System. out (672): Thread-12 => 10
11-17 22:45:01. 264: I/System. out (672): Thread-12 => 9
11-17 22:45:01. 264: I/System. out (672): Thread-12 => 8
11-17 22:45:01. 264: I/System. out (672): Thread-12 => 7
11-17 22:45:01. 264: I/System. out (672): Thread-12 => 6
11-17 22:45:01. 274: I/System. out (672): Thread-12 => 5
11-17 22:45:01. 274: I/System. out (672): Thread-12 => 4
11-17 22:45:01. 274: I/System. out (672): Thread-12 => 3
11-17 22:45:01. 274: I/System. out (672): Thread-12 => 2
11-17 22:45:01. 274: I/System. out (672): Thread-12 => 1

Analysis:
The running results are inconsistent with expectations. The analysis shows that each of the three threads sells their own 10 tickets instead of the same 10 tickets.

2. modify the code in onClick and analyze the running result.

Public void onClick (View v) {// instantiate the Thread object MyThread myThread = new MyThread (); new Thread (myThread, "Window 1 "). start (); new Thread (myThread, "window 2 "). start (); new Thread (myThread, "window 3 "). start ();}

Running result:

11-17 22:49:17. 314: I/System. out (708): window 3 ==> 10
11-17 22:49:17. 314: I/System. out (708): window 3 => 9
11-17 22:49:17. 314: I/System. out (708): window 3 => 8
11-17 22:49:17. 314: I/System. out (708): window 3 ==> 7
11-17 22:49:17. 314: I/System. out (708): window 3 => 6
11-17 22:49:17. 324: I/System. out (708): window 3 ==> 5
11-17 22:49:17. 324: I/System. out (708): window 3 => 4
11-17 22:49:17. 324: I/System. out (708): window 3 ==> 3
11-17 22:49:17. 324: I/System. out (708): window 3 ==> 2
11-17 22:49:17. 324: I/System. out (708): window 3 ==> 1

Analysis:
The three windows are already selling a total of 10 tickets, but because there is no thread synchronization, a thread window will be randomly selected to sell tickets until they are sold out, as a result, other Windows cannot be sold.

3. modify the code below to verify my guess.

Public void onClick (View v) {// instantiate the Thread object MyThread myThread = new MyThread (); new Thread (myThread, "Window 1 "). start (); new Thread (myThread, "window 2 "). start (); new Thread (myThread, "window 3 "). start ();} class MyThread extends Thread {private int tickets = 10; public void run () {for (int I = 0; I <200; I ++) {synchronized () ;}} public synchronized void synchronized () {if (tickets> 0) {System. out. println (Thread. currentThread (). getName () + "=>" + tickets --);}}}

Running result:

05-11 08:53:31. 986: INFO/System. out (7116): Window 1 => 10
05-11 08:53:32. 006: INFO/System. out (7116): Window 1 => 9
05-11 08:53:32. 066: INFO/System. out (7116): Window 1 => 7
05-11 08:53:32. 086: INFO/System. out (7116): Window 1 => 6
05-11 08:53:32. 106: INFO/System. out (7116): Window 1 => 5
05-11 08:53:32. 106: INFO/System. out (7116): Window 1 => 4
05-11 08:53:32. 126: INFO/System. out (7116): Window 1 => 3
05-11 08:53:32. 146: INFO/System. out (7116): Window 1 => 2
05-11 08:53:32. 146: INFO/System. out (7116): Window 1 => 1

Analysis:
An object has only one lock. Therefore, if a thread acquires the lock, no other thread can obtain the lock until the thread is released (or returned. This also means that no other thread can enter the synchronized method or code block on the object until the lock is released.
Releasing a lock means that the lock thread has exited the synchronized synchronization method or code block.
The above Code does not have Thread. sleep (10). In other words, Thread 1 is always in the running state, no lock is released, and no chance for other threads to run.

4. Based on the above analysis, modify the Code as follows:

Public void onClick (View v) {// instantiate the Thread object MyThread myThread = new MyThread (); new Thread (myThread, "Window 1 "). start (); new Thread (myThread, "window 2 "). start (); new Thread (myThread, "window 3 "). start ();} class MyThread extends Thread {private int tickets = 10; public void run () {for (int I = 0; I <200; I ++) {try {retry (); Thread. sleep (10);} catch (InterruptedException e) {System. out. println ("I was interrupted" + Thread. currentThread (). getName (); e. printStackTrace () ;}} public synchronized void Merge () {if (tickets> 0) {System. out. println (Thread. currentThread (). getName () + "=>" + tickets --);}}}

Running result:

05-11 09:17:07. 496: INFO/System. out (7898): Window 1 => 10
05-11 09:17:07. 528: INFO/System. out (7898): Window 1 => 9
05-11 09:17:07. 546: INFO/System. out (7898): Window 1 => 8
05-11 09:17:07. 577: INFO/System. out (7898): Window 1 => 7
05-11 09:17:07. 626: INFO/System. out (7898): window 3 ==> 6
05-11 09:17:07. 626: INFO/System. out (7898): window 2 ==> 5
05-11 09:17:07. 636: INFO/System. out (7898): Window 1 => 4
05-11 09:17:07. 646: INFO/System. out (7898): window 2 ==> 3
05-11 09:17:07. 646: INFO/System. out (7898): Window 1 => 2
05-11 09:17:07. 656: INFO/System. out (7898): window 3 ==> 1

Analysis:
This is exactly what we want. Now we know how the train station sells tickets.

// Some may not quite understand the synchronized usage in the above program, so let's continue to look down

Synchronized usage

1. Used for method declaration, placed after the range operator (public, etc.), before the return type declaration (void, etc. That is, only one thread can enter this method at a time. If other threads want to call this method at this time, they can only wait in queue. After the current thread (that is, the thread inside the synchronized Method) executes this method, other threads can enter.
For example:

Public synchronized void synMethod () {// method body}

2. For a code block, synchronized is followed by parentheses and contains variables. In this way, only one thread enters the code block at a time. For example:

Public int synMethod (int a1) {synchronized (a1) {// only one thread can enter

Focus on technology, enjoy life! -- QQ: 804212028.
Link: http://blog.csdn.net/y18334702058/article/details/44624305

Related Article

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.