Java multithreading - synchronization of threads (synchronization method)

Thread synchronization is a means of ensuring that multiple threads safely access competing resources .
Thread synchronization is a difficulty in Java multi-threaded programming. Often developers do not know what is a competing resource, when to consider synchronization, how to synchronize, etc. Of course, there is no clear answer to these questions, but some principles need to be considered. , is there a problem with competing resources being changed at the same time?

Before this article, please refer to " Java Multithreading - Thread Synchronization and Locking " on which this article is written.

For synchronization, the following two operations need to be completed in the specific Java code:
marking the resource that competes for access as private;
synchronizing the code that modifies the variable, using the synchronized keyword to synchronize the method or code.
Of course this is not the only way to control concurrency safety.

Synchronized keyword usage description
synchronized can only mark non-abstract methods, not member variables.

In order to demonstrate the use of the synchronization method, a credit card account is constructed with a credit limit of 100w at first, and then multiple operations such as overdraft and deposit are simulated. Obviously, the bank account User object is a competing resource, and the account method oper(int x) is used for multiple concurrent operations. Of course, synchronization should be added to this method, and the account balance should be set as a private variable to prohibit direct access.

copy code
package cn.thread;

/**
 * Thread synchronization method
 *
 * @author Lin Jiqin
 * @version 1.0 2013-7-24 上午10:12:47
 */
public class ThreadSynchronizedMethod {
    public static void main(String[] args) {
        ThreadSynchronizedMethod t = new ThreadSynchronizedMethod();
        User u = t.new User("张三", 100);
        MyThread t1 = t.new MyThread("线程A", u, 20);
        MyThread t2 = t.new MyThread("线程B", u, -60);
        MyThread t3 = t.new MyThread("线程C", u, -80);
        MyThread t4 = t.new MyThread("线程D", u, -30);
        MyThread t5 = t.new MyThread("线程E", u, 32);
        MyThread t6 = t.new MyThread("线程F", u, 21);

        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
    }

    class MyThread extends Thread {
        private User u;
        /**存款金额*/
        private int y = 0;
        
        MyThread(String name, User u, int y) {
            super(name);
            this.u = u;
            this.y = y;
        }

        public void run() {
            u.oper(y);
        }
    }

    class User {
         /** Account */ 
        private String code;
         /** Balance */ 
        private  int cash;

        User(String code, int cash) {
            this.code = code;
            this.cash = cash;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        /**
         * deposit
         *
         * @param x deposit amount
         *            
         */
        public synchronized void oper(int x) {
            try {
                Thread.sleep(10L);
                this.cash += x;
                System.out.println( "Thread"+Thread.currentThread().getName() + "End of operation, add "" + x
                         + "", the current user account balance is: " + cash);
                Thread.sleep(10L);
            } catch (InterruptedException e) {
                e.printStackTrace ();
            }
        }

        @Override
        public String toString() {
            return "User{" + "code='" + code + '\'' + ", cash=" + cash + '}';
        }
    }
}
copy code

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326238298&siteId=291194637
Recommended