Java Multithreaded Instances

Source: Internet
Author: User

The multithreading mechanism of Java

Example one:

Title: There are three threads to print a, B, C, please use multi-threaded programming, on-screen cycle printing 10 times Abcabc...public class sleepexample extends thread  {          private static int  currentcount = 0;          public  Sleepexample (String name)  {            This.setname (name);       }           @Override      public void run ()  {            while  (currentcount < 30)  {                switch  (currentcount % 3)  {               case 0:                    if  ("A". Equals (GetName ()))  {                      system.out.print ("A");                  currentCount++;                 }                    break;                case 1:                    if  ("B". Equals (GetName ()))  {                      System.out.print ("B");                  currentcount++;                 }                    break;                case 2:                    if  ("C". Equals (GetName ()))  {                     system.out.print ("C");                  currentCount++;                 }                    break;                }           }           }         public  Static void main (String[] args)  {            new sleepexample ("A"). Start ();            new sleepexample ("B"). Start ();            new  sleepexample ("C"). Start ();       }       }

Instance two:

Write a program to get two threads into a deadlock Public class deadlockexample {    string resource1  =  "Resource 1";    string resource2 =  "Resource 2";     Thread t1 = new thread ("Thread 1")  {        public  void run ()  {            while   (True)  {                 synchronized  (Resource1)  {                     synchronized  (RESOURCE2)  {                       &NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Thread 1 has" +resource1+ "  needs" +resource2);                     }                 }             }        }    };     thread t2 = new thread ("Thread 2")  {         Public void run ()  {             while  (True)  {                 synchronized  (RESOURCE2)  {                     synchronized  (Resource1)  {                          systeM.OUT.PRINTLN ("Thread 2 has" +resource2+ "  needs" +resource1);                     }                 }             }        }    };      public static void main (string a[])  {     Deadlockexample test = new deadlockexample ();         test.t1.start ();         test.t2.start ();     } }

Instance three:

import java.util.concurrent.executorservice;import java.util.concurrent.executors;import  java.util.concurrent.locks.condition;import java.util.concurrent.locks.lock;import  java.util.concurrent.locks.reentrantlock;//One thread prints the  1~52, the other thread prints the letter A-Z. Print order is 12a34b56c ... 5152zpublic class threadcommunicationtest {          private final lock lock = new reentrantlock ();          private final condition conditiona = lock.newcondition ( );      private final condition conditionb =  Lock.newcondition ();         private static char  currentthread =  ' A ';         public static  Void main (String[] args)  {             threadcommunicationtest test = new  Threadcommunicationtest ();              Executorservice service = executors.newcachedthreadpool ();              service.execute (Test.new runnablea ());           service.execute (Test.new runnableb ());              service.shutdown ();          }         private class RunnableA  implements runnable {              Public void run ()  {               for  (int i = 1; i <= 52; i++)  {                   lock.lock ();                      try {                        while  (currentthread !=  ' A ')  {                            try {                               conditiona.await ();                            } catch  (interruptedexception e)  {                                // TODO Auto-generated catch block                                e.printstacktrace ();                            }                       }                          system.out.println (i);                       if  (i %  2 == 0)  {                           currentThread =  ' B ';                            conditionb.signal ();                       }                   } finally  {                       lock.unlock ();                   }              }              }          }         private class runnableb  implements Runnable {               @Override          public void run ()  {               for  (char c =   ' A '; c <=  ' Z ';  c++)  {                   lock.lock ();                   try {                       while  (currentThread !=   ' B ')  {                           try {                                conditionb.await ();                           }  catch  (interruptedexception e)  {                                // TODO Auto-generated catch block                                e.printstacktrace ();                           }                       }                           system.out.println (c);                       currentThread =  ' A ';                        conditiona.signal ();                   } finally {                       lock.unlock ();                   }               }              }         } }


Please refer to http://blog.sina.com.cn/s/blog_6d5c82a70100m30t.html for multi-threaded explanation


650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0006.gif "alt=" J_0006.gif "/>

This article is from a "stroll," blog, please be sure to keep this source http://macxiao.blog.51cto.com/9606147/1591564

Java Multithreaded Instances

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.