Small multi-threaded demos and multi-threaded demos

Source: Internet
Author: User

Small multi-threaded demos and multi-threaded demos
1. Single lock of multiple threads

Package com. sun. multithread. sync; public class MyThread extends Thread {private int count = 5; // lock public synchronized void run () {count --; System. out. println (this. currentThread (). getName () + "count =" + count);} public static void main (String [] args) {MyThread myThread = new MyThread (); Thread t1 = new Thread (myThread, "t1"); Thread t2 = new Thread (myThread, "t2"); Thread t3 = new Thread (myThread, "t3"); Thread t4 = new Thread (myThread, "t4"); Thread t5 = new Thread (myThread, "t5"); t1.start (); t2.start (); t3.start (); t4.start (); t5.start ();}}
2. Multiple Threads and multiple locks
Package com. sun. multithread. sync; public class MultiThread {private static int num = 0;/*** Add the synchronized keyword to the static method to lock the class, category-Level Lock * the lock obtained by the key word synchronized is an object lock, instead of using a code (method) as a lock. * So which thread in the Code executes the method of the synchronized keyword first, which thread holds the lock of the object to which the method belongs ** @ param tag parameter */public static synchronized void printNum (String tag) {try {if (tag. equals ("a") {num = 100; System. out. println ("tag a, set num over! "); Thread. sleep (1000);} else {num = 200; System. out. println (" tag B, set num over! ");} System. out. println ("tag" + tag + ", num =" + num);} catch (InterruptedException e) {e. printStackTrace () ;}} public static void main (String [] args) {// two different objects final MultiThread m1 = new MultiThread (); final MultiThread m2 = new MultiThread (); Thread t1 = new Thread (new Runnable () {@ Override public void run () {m1.printNum ("");}}); thread t2 = new Thread (new Runnable () {@ Override public void run () {m1.printNum ("B") ;}}); t1.start (); t2.start ();}}

 

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.