1. Multi-threaded data security
Class MyThread implements Runnable{int i = 100;public void Run {while (true) {//thread.currentthread (); Gets the thread in which the current thread is running 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 ();//Generate two thread objects, But these two thread objects share the same thread body thread t1 = new Thread (); Thread t2 = new Thread (),//each thread must have a name, the thread name can be set by the SetName () method of the Thread object, or the GetName method can be used to get the name T1.setname of the thread ("Thread A"); T2.setname ("thread B"); T1.start (); T2.start ();}}
sometimes it goes wrong: {Thread A 100 thread B 100 ...}
Workaround, add a synchronous 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 line enters upgradeable obtains this lock, which thread has the right to execute this code, the other thread can only wait for <span style= "White-space:pre" ></span>//a thread executes a piece of code, Another thread will no longer execute this code//thread.currentthread (); Gets the thread in which the current thread is running System.out.println (Thread.CurrentThread (). GetName () + i); i--; Thread.yield (); if (I < 0) {break;}}}}
2. Methods for synchronizing threads
Threads in Java (iii)