Multi-threaded data security: ensuring data integrity Methods for
synchronizing threads
Modified sync code
In addition to the synchronization code block, synchronized can also be used to synchronize methods, functions is similar, such as:
synchronizing threads
class MyThread implements Runnable{ int i=100; public void run(){//Rewrite the run method while(true) { //Print the name of the current thread and the value of the i variable 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 objects share a thread body Thread t1 = new Thread(myThread); Thread t2 = new Thread(myThread); //Each thread has a name, you can set the name of the thread through the setName() of the Thread object //You can also use the getName method to get the name of the thread t1.setName("Thread A"); t2.setName("Thread B"); // start two threads separately t1.start(); t2.start(); } }The running result is as follows
Thread-->B11 Thread-->A10 Thread-->B9 Thread-->A8 Thread-->B7 Thread-->A5 Thread-->B5 Thread-->A4 Thread-->B3 Thread-->A2 Thread-->B1 Thread-->A0It is found that data is lost and repeated errors. This is the error that occurs when multiple threads share the same data. At this time, thread synchronization is required.
Modified sync code
public void run(){ while(true) { /* use synchronized code blocks */ synchronized(this){ System.out.println(Thread.currentThread().getName() + i); i--; Thread.yield();/*让出CPU*/ if(i<0) break; } } }When synchronized is used, once a thread acquires the synchronization lock of an object, all the synchronized code on the object will be locked and cannot be used by other threads.
In addition to the synchronization code block, synchronized can also be used to synchronize methods, functions is similar, such as:
public synchronized void fun() { }By Urien April 14, 2018 14:02:27