Java threads (3)
1. multi-threaded Data Security
Class MyThread implements Runnable {int I = 100; public void run {while (true) {// Thread. currentThread (); obtain the thread in which the current thread runs the System. out. println (Thread. currentThread (). getName () + I); I --; Thread. yield (); if (I <0) {break ;}}}}
Class Test {public static void main (String args []) {MyThread myThread = new MyThread (); // generates two Thread objects, however, these two Thread objects share the same Thread body Thread t1 = new Thread (); Thread t2 = new Thread (); // each Thread must be named, you can use the setName () method of the Thread object to set the Thread name, or use the getName method to obtain the Thread name t1.setName ("Thread a"); t2.setName ("Thread B "); t1.start (); t2.start ();}}
Sometimes an error occurs: {thread a 100 thread B 100 ...}
Solution: add the synchronization code block to the MyThread class.
Class MyThread implements Runnable {int I = 100; public void run {while (true) {synchronized (this) {// synchronized is a lock, which thread obtains the lock first, which Thread has the right to execute this code, and the other Thread can only wait // when one Thread is executing a code segment, the other Thread will no longer execute this code segment // Thread. currentThread (); obtain the thread in which the current thread runs the System. out. println (Thread. currentThread (). getName () + I); I --; Thread. yield (); if (I <0) {break ;}}}}}
2. synchronous thread method