multithreaded one

Asynchronous: t1 thread executes t1, t2 thread executes t2, no one waits between the two threads
Synchronous programming model: t1 thread and t2 thread execute, t1 thread must wait for the t2 thread to execute before the t1 thread can execute, This is synchronous programming, the model

When do you need to synchronize?
1. Data security is required. The thread synchronization mechanism makes the program (equivalent to) single-threaded
2. Under what conditions is synchronization used?
(1). Must be a multi-threaded environment
(2). Multi-threaded environments share the same data
(3). Shared data and modification operations


public class Account {

    private String actno;
    private double balance;

    public Account(String actno, double balance) {
        super();
        this.actno = actno;
        this.balance = balance;
    }

    public String getActno() {
        return actno;
    }

    public void setActno(String actno) {
        this.actno = actno;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public String drawMoney(double money) {
        // 括号里面的是共享对象 就是这个账户
        // 让synchronized括号里面的代码永远只有一个线程执行
        synchronized (this) {
            if (this.balance - money < 0) {
                return "余额不足";
            } else {
                this.balance -= money;
                return "取款 " + money + " 成功";
            }
        }

    }

    public void saveMoney(double money) {
        this.balance += money;
    }

}


public class Porcessor implements Runnable{

    Account account;
    public Porcessor(Account account) {
        this.account = account;
    }
    @Override
    public void run() {
        System.out.println(account.drawMoney(3000.0));
    }

}

public class Test {

    public static void main(String[] args) {
        Account act = new Account("cc-001", 5000);
        Porcessor p = new Porcessor(act);

        Thread t1 = new Thread(p);
        Thread t2 = new Thread(p);
        t1.start();
        t2.start();
    }
}

//结果
//取款 3000.0 成功
//余额不足

Principle: When the t1 thread executes here, and encounters the synchronized keyword, it will look for the object lock of this. If it finds the object lock of this, it will enter the synchronization statement block to execute the program. When the code in the synchronized block is executed, the t1 thread returns the object lock of this

In the process of the t1 thread executing the synchronized statement block, if the t2 thread also comes to execute the following code, it also encounters the synchronized keyword, so it also looks for the object lock of this, but the object is held by the t1 thread, and can only wait here for this Return of the object.

public class RunnableDemo implements Runnable{

    MyClass mc;

    public RunnableDemo(MyClass mc) {
        this.mc = mc;
    }

    @Override
    public void run() {

        try{
            if(Thread.currentThread().getName().equals("t1")) mc.method1();
            if(Thread.currentThread().getName().equals("t2")) mc.method2();

        }catch (Exception e) {
            System.out.println("Thread "+ (Thread.currentThread().getName()) + " interrupted.");
        }
        System.out.println("Thread " + (Thread.currentThread().getName()) + " exiting.");
    }

}


public class MyClass {

    //因为是共享对象,t1线程拿走了对象锁
    public synchronized void method1(){
        System.out.println("method1....");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //t2线程想要执行,但是对象锁被t1拿走了,所以只有等待t1线程执行完毕才能执行
    public synchronized void method2(){
        System.out.println("method2....");
    }
}

public class Test {

    public static void main(String[] args) throws InterruptedException {
        RunnableDemo rd = new RunnableDemo(new MyClass());
        Thread t1 = new Thread(rd);
        Thread t2 = new Thread(rd);
        t1.setName("t1");
        t2.setName("t2");

        t1.start();
        Thread.sleep(1000);
        t2.start();
    }
}

//结果
//method1....
//method2....
//Thread t1 exiting.
//Thread t2 exiting.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326767451&siteId=291194637