Synchronization with the thread deadlock: java multithreading three

Article Source https://www.jianshu.com/p/b913e64db7ee

Articles corresponding video source: https://developer.aliyun.com/course/1012?spm=5176.10731542.0.0.6ef2d290hxQ4g0

Among the multi-threaded processing, you can use multiple threads operating resources Runnable description, and Thread describe each thread object, of course, when multiple threads access the same resources if not handled properly, will produce erroneous operation data.

Leads to synchronization problems

  Write a simple program is now selling tickets, the number of threads processing operations to achieve the object of selling tickets.
Example: to achieve operational sell tickets

class MyThread implements Runnable {
    private int ticket = 10;//总票数为10张
    @Override
    public void run() {
        while (true) {
            if (this.ticket > 0) {
                System.out.println(Thread.currentThread().getName() + "卖票,ticket = " + this.ticket--);
            } else {
                System.out.println("***** 票卖光了 *****");
                break;
            }
        }
    }
}
public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        MyThread mt=new MyThread();
        new Thread(mt,"票贩子A").start();
        new Thread(mt,"票贩子B").start();
        new Thread(mt,"票贩子C").start();
    }
}

  At this point the program will create three thread objects, and these three threads 10 tickets will be sold. At this time, the processing procedure performed when the ticket, and there is no problem (artifacts), the following operation can simulate what delay the ticket.

class MyThread implements Runnable {
    private int ticket = 10;//总票数为10张
    @Override
    public void run() {
        while (true) {
            if (this.ticket > 0) {
                try {
                    Thread.sleep(100);//模拟网络延迟
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "卖票,ticket = " + this.ticket--);
            } else {
                System.out.println("***** 票卖光了 *****");
                break;
            }
        }
    }
}

 This time delay is added to the problem is exposed, and in fact this issue has been in.

 

Thread Synchronization

  The main reason can be determined after analysis has produced a synchronization problem, then the following would need to solve the synchronization problem, but the key to solving the problem is to lock, referring to the time when one thread to perform an operation, other threads waiting outside;

 To implement the program lock function can be used to absorb synchronized keyword, using the synchronization method and a synchronization synchronized code blocks may be defined, the operation code in the sync block allows only one thread of execution.
1, the synchronization code block using the following conditions:

synchronized (同步对象){
    同步代码操作;
}

 When the object is generally to synchronization processing, synchronization can be performed using the current object this.
  Example: synchronous data synchronization code block access problems to solve

class MyThread implements Runnable {
    private int ticket = 1000;//总票数为10张
    @Override
    public void run() {
        while (true) {
            synchronized (this) {//每一次只允许一个线程进行访问
                if (this.ticket > 0) {
                    try {
                        Thread.sleep(100);//模拟网络延迟
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "卖票,ticket = " + this.ticket--);
                } else {
                    System.out.println("***** 票卖光了 *****");
                    break;
                }
            }
        }
    }
}
public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        MyThread mt = new MyThread();
        new Thread(mt, "票贩子A").start();
        new Thread(mt, "票贩子B").start();
        new Thread(mt, "票贩子C").start();
    }
}

  After the addition of the synchronization process, the overall performance of the program declined. Synchronization will actually result in decreased performance .
2, using the synchronization method to solve: just use the synchronized keyword can be defined in the method.

class MyThread implements Runnable {
    private int ticket = 10;//总票数为10张
    public synchronized boolean sale() {
        if (this.ticket > 0) {
            try {
                Thread.sleep(100);//模拟网络延迟
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "卖票,ticket = " + this.ticket--);
            return true;
        } else {
            System.out.println("***** 票卖光了 *****");
            return false;
        }
    }
    @Override
    public void run() {
        while (this.sale()) {}
    }
}
public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        MyThread mt = new MyThread();
        new Thread(mt, "票贩子A").start();
        new Thread(mt, "票贩子B").start();
        new Thread(mt, "票贩子C").start();
    }
}

 In future learning Java class libraries, it is a synchronization method uses synchronous processing system used in many classes.

Deadlock

  Deadlock is under way multithreading synchronization there is a problem that may arise, so-called deadlock refers to the number of threads waiting for each other state.

public class DeadLock implements Runnable {
    private Producer producer = new Producer();
    private Customer customer = new Customer();
    public DeadLock() {
        new Thread(this).start();
        customer.say(producer);
    }
    public static void main(String[] args) {
        new DeadLock();
    }
    @Override
    public void run() {
        producer.say(customer);
    }
}
class Producer {
    public synchronized void say(Customer customer) {
        System.out.println("店员:先买单后吃饭");
        customer.get();
    }
    public synchronized void get() {
        System.out.println("收到钱,可以给你做饭了");
    }
}
class Customer {
    public synchronized void say(Producer producer) {
        System.out.println("顾客:先吃饭后买单");
        producer.get();
    }
    public synchronized void get() {
        System.out.println("吃饱饭了,可以买单了");
    }
}

 The main reason is because the current deadlock caused all waiting for each other, waiting for the other to let out the resources. Deadlock is actually uncertain state of a development that appears, sometimes code is not handled properly, it will from time to time deadlock, which is a problem debugging normal development.
  Be sure to synchronize when a number of threads access the same resource, but too much will cause synchronization deadlock.

 

 

 

Published 52 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/YKWNDY/article/details/104644565