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 ();}}