synchronized: internal lock

synchronized: internal lock

Origin: parallel program development involves a multi-threaded, collaboration and data sharing between multi-tasking

A) internal lock: synchronized

1). The method defined in

public synchronized void method()

When the method is called, the calling thread must acquire the current lock object.

Lock objects: the current object.

2) The synchronization block

synchronized(Object obj){ }

Lock object: a common custom lock object used.

benefit:

1. The sync block can be more precise control of the synchronization code range

2. A small block of code lock Kuaijinkuaichu very beneficial, assuming code segment before and after the sync block are more time-consuming, and it

Who has no need to synchronize, then these codes into the whole synchronous code block will increase the locks, etc.

Waiting time.

Synchronization 3). Static method

public synchronized static method()

Lock Object: Class Object

4) Use the wait (), notify () to create a blocking queue

Construct:

Method 1: When the queue data, remove the first element, when there is no data, the thread enters a wait state, the line

Cheng is blocked.

Method Two: Add an object into the queue and wait for the notification method.

Use wait (), notify () to achieve the collaboration and sharing of data between multiple threads.

Analog queue:

/**
 * 使用synchronize和wait(), notify()实现一个阻塞队列
 * 实现:
 *    获取队列中的元素: 使用pop操作队列,当队列中有元素,则取出第一个元素,若队列为空,线程进入等待状态
 *    使用put()方法添加元素,并唤醒等待的线程
 */
public class BlockQueue {
    List list = new ArrayList<>();
    public synchronized Object pop() throws InterruptedException {
        //当涉及条件判断时,wait方法要在一个循环中使用,并指出跳出循环的条件
        //原因:若使用if语句,线程被唤醒,直接执行接下的业务逻辑,不再进行list.size() == 0的判断,若之前队列的
        //元素被消费,此时又再次唤醒该线程,队列中无数据,执行业务逻辑出错。
        //将wait()放入while中,唤醒线程后会再次进行条件判断,条件满足则执行业务逻辑。
        if(list.size() == 0) {
            this.wait();
        }
        if(list.size() > 0){
            System.out.println("取值");
            return list.remove(0);
        }else{
            return null;
        }
    }

    public synchronized void put(Object obj){
        list.add(obj);
        this.notify();
    }
}

test:

public class ThreadPoolTest {
    public static void main(String[] args) {
        BlockQueue queue = new BlockQueue();
        //两个线程,一个线程获取队列的数据,如果队列有数据则获取数据,如果没有则等待
        /**
         *  使用线程池来创建线程对象
         */
        ExecutorService executor = Executors.newFixedThreadPool(10);
        //线程一,取数据
        executor.execute(new Runnable(){
            @Override
            public void run(){
                while(true) {
                    //获取队列的数据
                    try {
                        queue.pop();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        executor.execute(new PopThread(queue));
        //线程二,放数据
        executor.execute( new Runnable(){
            @Override
            public void run(){
                while(true) {
                   String a = "1";
                    queue.put(a);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }


}

Guess you like

Origin www.cnblogs.com/Auge/p/11759944.html