Java multi-threading operation in Android development
Source: Internet
Author: User
<span id="Label3"></p><p><p>The common thread-related operations in Java are to determine whether threads are started, thread enforcement, thread hibernation, thread breaks, thread concessions, thread synchronization, and so On. Here are one by one examples.</p></p><p><p>first, we create a new Mythread class to implement the Runnable Interface. A thread-related operation based on this interface.</p></p><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">Class MyThread implements Runnable {public void run () {for (int i = 0; i < 3; i++) {System.out.println (THREAD.CURRENTTH Read (). getName () + "run" + i);}}}</pre></pre><p><p><strong><span style="font-size: medium;">1. Determine if the thread is started</span></strong></p></p><p><p>It is easy to determine whether a thread is started, through the thread.isalive () method.</p></p><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; highlight: [6,8]; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; highlight: [6,8]; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">public class Test {public static void main (string[] Args) {MyThread mt = new MyThread (); Thread t = new Thread (mt); System.out.println ("thread" + (t.isalive ()?) "already": "not") + "start"); T.start (); System.out.println ("thread" + (t.isalive ()?) "already": "not") + "start");}}</pre></pre><p><p>Output in:</p></p><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">Thread does not start thread has started Thread-0 run 0thread-0 run 1thread-0 Run 2</pre></pre><p><p><strong><span style="font-size: medium;">2. Thread Enforcement</span></strong></p></p><p><p>Thread enforcement can be implemented through Thread.Join (). Let's start by looking at an example of a non-mandatory implementation</p></p><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; highlight: [10,12]; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; highlight: [10,12]; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">public class Test {public static void main (string[] Args) {MyThread mt1 = new MyThread (); MyThread mt2 = new MyThread (); thread T1 = new Thread (mt1); Thread t2 = new Thread (mt2), try {t1.start ();//t1.join (); t2.start ();//t2.join ();} catch (Exception e) {e.printstacktrace ();}}}</pre></pre><p><p>The program is entered as Follows:</p></p><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">Thread-0 Run 0thread-1 run 0thread-0 run 1thread-1 run 1thread-0 run 2thread-1 Run 2</pre></pre><p><p>We found that two threads were running in parallel, so the result of execution was two threads executing the resulting output and then inserting it into the output stream by Time. After we comment out the join, we find that the execution of the program changes To:</p></p><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">Thread-0 Run 0thread-0 run 1thread-0 run 2thread-1 run 0thread-1 run 1thread-1 Run 2</pre></pre><p><p>As you can see, the result of the execution is that thread 1 begins execution, and thread 2 begins execution after thread 1 finishes executing.</p></p><p><p><strong><span style="font-size: medium;">3. Thread hibernation</span></strong></p></p><p><p>Thread hibernation is implemented through Thread.Sleep (). This is a static method, so it needs to be called through the thread class, rather than through the instantiation of the Variable. In addition, calling sleep () may throw a interruptedexception exception, and we need to put it in a try-catch block to catch this Exception.</p></p><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; highlight: [11]; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; highlight: [11]; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">public class Test {public static void main (string[] Args) {MyThread mt = new MyThread (); Thread t = new Thread (mt); long stime = System.currenttimemillis (); t.start (); System.out.println (system.currenttimemillis ()-stime), try {thread.sleep (+);} catch (Exception e) { E.printstacktrace ();} System.out.println (system.currenttimemillis ()-stime);}}</pre></pre><p><p>The results of the program execution are:</p></p><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">0thread-0 Run 0thread-0 run 1thread-0 run 21000</pre></pre><p><p>Use System.currenttimemiles () to get the time the program is Running. We found that it took 1 seconds from the beginning of execution to the end, which is the time that main thread sleeps.</p></p><p><p><strong><span style="font-size: medium;">4. Thread Interrupt</span></strong></p></p><p><p>As mentioned in the previous section, threads can be interrupted during sleep and throw interruptedexception exceptions, and this thread break behavior can be achieved through Thread.Interrupt (). first, We move the time statistics to mythread, and then we perform a hibernation operation once per output within the Mythread.</p></p><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; highlight: [24]; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; highlight: [24]; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">Class MyThread implements Runnable {public void run () {long stime = System.currenttimemillis (); System.out.println (system.currenttimemillis ()-stime); for (int i = 0; i < 3; i++) {System.out.println (thread.currentt Hread (). getName () + "run" + i); try {thread.sleep (1000);} Catch (Exception e) {e.printstacktrace ();}} System.out.println (system.currenttimemillis ()-stime);}} public class Test {public static void main (string[] Args) {MyThread mt = new MyThread (); Thread t = new thread (mt); t.start (); t.interrupt ();}}</pre></pre><p><p>The program output is:</p></p><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">0thread-0 run 0java.lang.interruptedexception:sleep interruptedThread-0 run 1at java.lang.Thread.sleep (Native METHOD) at Mythread.run (test.java:9) at Java.lang.Thread.run (thread.java:745) Thread-0 run 22002</pre></pre><p><p>Program from start to finish, took 2 seconds or so, but clearly in the mythread dormant 3 times, One second each time, should run about 3 seconds. This is because when the thread first sleeps, the first sleep is interrupted by thread.interrupt within the main threads, so the sleep time is almost 0, the remaining two sleep is not interrupted, so the total execution time is about 2 seconds.</p></p><p><p><strong><span style="font-size: medium;">5. Thread Concession</span></strong></p></p><p><p>In some cases, thread concessions are required for threads to continue their operations while they wait for the execution of the rest of the threads to Execute. A thread's concession can be achieved by THREAD.YIELD.</p></p><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; highlight: [5]; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; highlight: [5]; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">Class MyThread implements Runnable {public void run () {for (int i = 0; i < 3; i++) {System.out.println (THREAD.CURRENTTH Read (). getName () + "run" + i); Thread.yield ();}}} public class Test {public static void main (string[] Args) {MyThread mt1 = new MyThread (); MyThread mt2 = new MyThread (); thread T1 = new Thread (mt1); Thread t2 = new Thread (mt2); t1.start (); t2.start ();}}</pre></pre><p><p>The output is:</p></p><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">Thread-0 Run 0thread-1 run 0thread-0 run 1thread-1 run 1thread-0 run 2thread-1 Run 2</pre></pre><p><p><strong><span style="font-size: medium;">6. Thread Synchronization</span></strong></p></p><p><p>Java thread synchronization can be done using synchronous methods and synchronous code Blocks:</p></p><p><p><strong>(1) Synchronization method</strong></p></p><p><p>Let's start by observing the execution results of a Program.</p></p><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">Class MyThread implements Runnable {private int Tic = 5; @Overridepublic void run () {for (int i = 0; i < 3; i++) if (tic > 0) System.out.println (thread.currentthread (). getName () + "Ticket:" + tic--);}} public class Test {public static void main (string[] Args) {MyThread mt = new MyThread (), for (int i = 0; i < 3; i++) {ne W Thread (mt). start ();}}}</pre></pre><p><p>The result of the execution is:</p></p><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">Thread-1 ticket:5thread-2 ticket:3thread-0 ticket:4thread-2 ticket:1thread-1 ticket:2</pre></pre><p><p>We found that the result is that 3 threads are executed in parallel, and while thread 0 is running, thread 2 still has access to the inside of the method body and Vice Versa. Sometimes (for example, the ticketing System) we need to perform thread synchronization and mutex operations when one thread is running and another thread is unable to get inside the running method body. You can specify a method as a synchronous method by adding synchronized in front of the Method.</p></p><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; highlight: [5]; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; highlight: [5]; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">Class MyThread implements Runnable {private int Tic = 5; @Overridepublic synchronized void run () {for (int i = 0; i < 3; I++) if (Tic > 0) System.out.println (thread.currentthread (). getName () + "Ticket:" + tic--);}}</pre></pre><p><p>At this point the program runs as Follows:</p></p><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">Thread-0 ticket:5thread-0 ticket:4thread-0 ticket:3thread-2 ticket:2thread-2 ticket:1</pre></pre><p><p>As can be seen, after the increase in synchronization, the ticket is a one sold out, so that can effectively avoid the situation of the Re-votes.</p></p><p><p><strong>(2) Synchronizing code blocks</strong></p></p><p><p>We will change the above code to read as Follows. The same functionality can still be achieved</p></p><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; highlight: [7]; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; highlight: [7]; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">Class MyThread implements Runnable {private int Tic = 5; @Overridepublic void run () {synchronized (this) {for (int i = 0; I < 3; I++) if (Tic > 0) System.out.println (thread.currentthread (). getName () + "Ticket:" + tic--);}}}</pre></pre><p><p><strong>(3) Note</strong></p></p><p><p>1) when a thread is accessing an object's synchronized method, other threads cannot access the Object's other synchronized methods. The reason is simple because an object has only one lock, and when a thread acquires the lock on the object, the other thread cannot get the lock on the object, so the other synchronized methods of the object cannot be Accessed.</p></p><p><p>2) when a thread is accessing an object's synchronized method, other threads can access the Object's non-synchronized method. The reason is simple, access to the Non-synchronized method does not need to obtain the lock of the object, if a method does not use the Synchronized keyword decoration, It is not used to critical resources, then other threads can access this method,</p></p><p><p>3) if a thread a needs to access the Synchronized method Fun1 of the object object1, another thread B needs to access the Synchronized method Fun1 of the object object2, even if Object1 and Object2 are the same type), There is no thread-safety problem because they are accessing different objects, so there is no mutex problem.</p></p><p><p><strong><span style="font-size: medium;">6. Producer and Consumer issues</span></strong></p></p><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; highlight: [12,17,25,28,33,41]; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">Class Breadcontainer {public static final int maxnum = 300;private int num;public breadcontainer () {}public Breadcontainer (int Num) {this.num = num;} Public synchronized void Producebread (int. pdcnum, String producer) {while (num + pdcnum > Maxnum) {System.out.println (PR Oducer + "to produce" + pdcnum + ", sufficient resources without production, into the Waiting. "); try{this.wait ();} Catch (Exception e) {e.printstacktrace ();}} num + = pdcnum; System.out.println (producer + "produced" + pdcnum + "one", existing "+ num +"); this.notifyall ();} Public synchronized void Consumerbread (int. csmnum, String consumer) {while (csmnum > Num) {System.out.println (consumer + "to consume" + csmnum + ", Insufficient resources can not be consumed, into the Waiting. "); try {this.wait ();} Catch (Exception e) {e.printstacktrace ();}} num-= csmnum; System.out.println (csmnum + "consumed" + csmnum + "one, existing" + num + "one"); this.notifyall ();}} Class Producer extends Thread {private int pdcnum;private breadcontainer bc;public Producer () {}public Producer (int pdcnum , Breadcontainer bc, String producer) {this.pdcnum = pdcnum;this.bc = Bc;this.setname (producer);} public void Run () {bc.producebread (pdcnum, this.getname ());}} Class Consumer extends Thread {private int csmnum;private breadcontainer bc;public Consumer () {}public Consumer (int csmnum , Breadcontainer bc, String consumer) {this.csmnum = CSMNUM;THIS.BC = Bc;this.setname (consumer);} public void Run () {bc.consumerbread (csmnum, this.getname ());}} public class Test {public static void main (string[] Args) {breadcontainer BC = new Breadcontainer (50); Producer p1 = new Producer (bc, "p1"); Producer P2 = new Producer (n, bc, "p2"); Producer p3 = new Producer (290, bc, "p3"); Consumer C1 = new Consumer (+, bc, "c1"); Consumer C2 = new Consumer (1.start, bc, "c2"), c1.start (), c2.start ();p ();p 2.start ();p 3.start ();}</pre><p><p>The output is:</p></p><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;"><pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">C1 to consume 70, insufficient resources can not be consumed, into the Waiting. P3 to produce 290, sufficient resources without production, into the Waiting. P2 produced 200, the existing 250 P1 produced 50, existing 300 80 consumption 80, the existing 220 p3 to produce 290, sufficient resources without production, into the Waiting. 70 consumption of 70, the existing 150 P3 to produce 290, sufficient resources without production, into the Waiting.</pre></pre><p><p>Java multi-threading operation in Android development</p></p></span>
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