Step by Step _android Development Course [10]_thread Study

Source: Internet
Author: User

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

    • Topic: Thread Learning
      -When a program is launched for the first time, Android initiates a corresponding main thread, which is primarily responsible for handling UI-related events such as user key events, User touch screen events, and screen drawing events. and distribute the relevant events to the corresponding components for processing. So the main thread is often called the UI thread.

Thread-to-process relationships:

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

There are two ways to create a thread:

1. Extending the Java.lang.Thread class
Extend the Java.lang.Thread class, which is to write the run () method to the thread:

Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid.util.Log;ImportAndroid.widget.TextView; Public  class mainactivity extends Activity {    PrivateTextView TextView;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); TextView = (TextView) Findviewbyid (R.id.textview);NewThread (NewRunnable () {@Override               Public void Run() {Message message=NewMessage (); message.what=1;              Handler.sendmessage (message);              }}). Start (); } Handler Handler =NewHandler () { Public void Handlemessage(Message msg) {Switch(Msg.what) { Case 1: Textview.settext ("Doodle"); Break; }Super. Handlemessage (msg); }    };}

2. Implement the Runnable interface
Let the class implement the Runnable interface and let the Run method stand out

Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid.widget.TextView; Public  class mainactivity extends Activity implements Runnable {    PrivateTextView TextView;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);       Setcontentview (R.layout.activity_main);       TextView = (TextView) Findviewbyid (R.id.textview); Thread thread =NewThread ();    Thread.Start (); } Handler Mhandler =NewHandler () { 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 stubMessage msg =NewMessage (); Msg.what =1;    Mhandler.sendmessage (msg); }}

Classic Thread Sell Ticket example: (Can let us understand the use of threads more)

Multiple Windows sell train tickets together. Suppose there are 3 windows at the same time ticket sales, a total of 10 train tickets for sale. Start three threads to sell a common 10 tickets.

1. We open three threads to sell tickets:

 Public  class commontestactivity extends Activity{    PrivateButton MyButton;PrivateTextView MyText;protected voidOnCreate (Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.main);        MyButton = (Button) Findviewbyid (R.id.button);        MyText = (TextView) Findviewbyid (R.id.text); Mybutton.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated method stubMyThread MyThread1 =NewMyThread (); MyThread mythread2=NewMyThread (); MyThread myThread3 =NewMyThread ();                 Mythread1.start ();                 Mythread2.start ();             Mythread3.start ();    }        }); } class MyThread extends Thread {        Private intTickets =Ten; Public voidRun () { for(inti =0; I < $; i++) {if(Tickets >0) {System.out.println (Thread.CurrentThread (). GetName () +"==>"+ tickets--); }            }        }    }}

Operation 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 results are inconsistent with expectations, and the analysis shows that 3 threads sell each of their 10 tickets, rather than the common 10 tickets.

2. Only modify the code inside the onclick and analyze the running results

publicvoid onClick(View v) {     //实例化线程对象     =new MyThread();     newThread"窗口1").start();     newThread"窗口2").start();     newThread"窗口3").start(); }

Operation 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:
Here 3 windows are already selling a common 10 tickets, but because there is no thread synchronization, will randomly select a thread window to execute sell tickets until sold out, resulting in other windows have no opportunity to sell.

3. Continue to modify the code below to verify that I have just guessed.

 Public voidOnClick (View v) {//Instantiating thread objectsMyThread MyThread =NewMyThread ();NewThread (MyThread,"Window 1"). Start ();NewThread (MyThread,"Window 2"). Start ();NewThread (MyThread,"Window 3"). Start (); } class MyThread extends Thread{     Private intTickets =Ten; Public voidRun () { for(inti =0; i< $;         i++) {sell (); }     } PublicSynchronizedvoidSell () {if(Tickets >0) {System.out.println (Thread.CurrentThread (). GetName () +"==>"+ tickets--); }     } }

Operation 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.016:
Info/system.out (7116): Window 1==>8 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. So, if a thread obtains the lock, no other thread can get the lock until the first thread releases (or returns) the lock. This also means that no other thread can enter the synchronized method or block of code on the object until the lock is freed.
A release lock is a lock thread that exits the synchronized synchronization method or code block.
The code above does not have Thread.Sleep (10), in other words the line Cheng is running, there is no release lock, no chance to run to other threads.

4. According to the above analysis, modify the code as follows:

 Public voidOnClick (View v) {//Instantiating thread objectsMyThread MyThread =NewMyThread ();NewThread (MyThread,"Window 1"). Start ();NewThread (MyThread,"Window 2"). Start ();NewThread (MyThread,"Window 3"). Start (); } class MyThread extends Thread{         Private intTickets =Ten; Public voidRun () { for(inti =0; i< $; i++) {Try{Sell (); Thread.Sleep (Ten); }Catch(Interruptedexception e) {System.out.println ("I was interrupted."+ Thread.CurrentThread (). GetName ());                 E.printstacktrace (); }            }         } PublicSynchronizedvoidSell () {if(Tickets >0) {System.out.println (Thread.CurrentThread (). GetName () +"==>"+ tickets--); }         }     }

Operation 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 the result we want, now know how the railway station is to sell tickets.

Some students may not understand the application of synchronized in the above procedures, then we continue to look down

Synchronized main usage

1. When the method declaration is used, it is placed before the scope operator (public, etc.) and returns the type declaration (void, etc.). That is, only one thread can enter the method at a time, and other threads will be able to invoke the method at this point, only queued, and the current thread (that is, the thread inside the Synchronized method) executes the method before other threads can enter.
For example:

publicsynchronizedvoidsynMethod() {//方法体}

2. For a block of code, synchronized followed by parentheses, in parentheses is a variable so that only one thread at a time enters that block of code. For example:

publicintsynMethod(int a1){synchronized(a1) {//一次只能有一个线程进入

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

Step by Step _android Development Course [10]_thread Study

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.