JUC concurrent programming (1)

1. What is JUC?

 

Business: ordinary thread code Thread

Runnable has no return value, and its efficiency is relatively low compared to Callable!

 

 

2. Threads and processes

Process: a program, a collection of QQ.exe, Music.exe programs

A process can often have multiple threads, including at least one

Java has two threads by default, main GC

Thread: open a process Typro, write, and save automatically (the thread is responsible)

Can java really start threads? can not open

 

Concurrency

Concurrent programming: concurrent, parallel

Concurrency (multiple threads operate on the same resource)

​ ·One CPU core, multi-threaded simulation, fast alternate

Parallel (multiple people walking together)

​ ·cpu multi-core, multiple threads can execute thread pool at the same time

package com.xizi.demo01;
public class Test {
    public static void main(String[] args) {
        //Get the number of cores of the cpu
        //cpu-intensive, IO-intensive
        System.out.println(Runtime.getRuntime().availableProcessors());
    }
}

The essence of concurrent programming: make full use of CPU resources


The thread has several states

public enum State {
    /**
     * Thread state for a thread which has not yet started.
     */
    NEW,
    //newborn
    /**
     * Thread state for a runnable thread.  A thread in the runnable
     * state is executing in the Java virtual machine but it may
     * be waiting for other resources from the operating system
     * such as processor.
     */
    RUNNABLE,
    //run
    /**
     * Thread state for a thread blocked waiting for a monitor lock.
     * A thread in the blocked state is waiting for a monitor lock
     * to enter a synchronized block/method or
     * reenter a synchronized block/method after calling
     * {@link Object#wait() Object.wait}.
     */
    BLOCKED,
    //block
    /**
     * Thread state for a waiting thread.
     * A thread is in the waiting state due to calling one of the
     * following methods:
     * <ul>
     *   <li>{@link Object#wait() Object.wait} with no timeout</li>
     *   <li>{@link #join() Thread.join} with no timeout</li>
     *   <li>{@link LockSupport#park() LockSupport.park}</li>
     * </ul>
     *
     * <p>A thread in the waiting state is waiting for another thread to
     * perform a particular action.
     *
     * For example, a thread that has called <tt>Object.wait()</tt>
     * on an object is waiting for another thread to call
     * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
     * that object. A thread that has called <tt>Thread.join()</tt>
     * is waiting for a specified thread to terminate.
     */
    WAITING,
    //Wait, take the stage hard
    /**
     * Thread state for a waiting thread with a specified waiting time.
     * A thread is in the timed waiting state due to calling one of
     * the following methods with a specified positive waiting time:
     * <ul>
     *   <li>{@link #sleep Thread.sleep}</li>
     *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
     *   <li>{@link #join(long) Thread.join} with timeout</li>
     *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
     *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
     * </ul>
     */
    TIMED_WAITING,
    //Timeout waiting
    /**
     * Thread state for a terminated thread.
     * The thread has completed execution.
     */
    TERMINATED;
    //Terminate 
}

wait/sleep difference

1. From different classes

​    wait=>Object

​    sleep=>Thread

2. About the release of the lock

​ Wait will release the lock, sleep will not release the lock

3. Yes, the scope is different

​ wait: must be in a synchronous code block

​ sleep: can sleep anywhere

4. Do you want to catch exceptions

​ wait: no need to catch exceptions

​ sleep: the exception must be caught

 

3.Lock lock

The traditional way to implement Runnable interface is too poorly coupled

 

 

Optimized traditional way to buy tickets

Synchronized

package com.xizi.demo01;
public class SaleTicketTest {
    public static void main(String[] args) {
        //并发:多个线程操作同一个资源,把资源丢入线程
        Ticket ticket = new Ticket();
        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                ticket.sale();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                ticket.sale();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                ticket.sale();
            }
        },"C").start();
    }
}
//资源类 OOP
class Ticket{
    //属性 方法
    private int number=30;
    //买票的方式
    //synchronizedd 本质:队列,锁
    public synchronized void sale(){
        if (number>0){
            System.out.println(Thread.currentThread().getName()+"卖出了第"+(number--)+"张票,剩余"+number+"张");
        }
    }
}

 

lock mode

package com.xizi.demo01;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SaleTicketTest2 {
    public static void main(String[] args) {
        //并发:多个线程操作同一个资源,把资源丢入线程
        Ticket2 ticket2 = new Ticket2();
        new Thread(()->{ for (int i = 0; i < 50; i++) ticket2.sale(); },"A").start();
        new Thread(()->{ for (int i = 0; i < 50; i++) ticket2.sale(); },"B").start();
        new Thread(()->{ for (int i = 0; i < 50; i++) ticket2.sale(); },"C").start();
    }
}
    //Lock 三部曲
//1.new ReentrantLock();
//2.lock.lock(); 加锁
//3.finally=>  lock.unlock();   解锁
class Ticket2 {
        //属性 方法
        private int number = 30;
        Lock lock = new ReentrantLock();
        //买票的方式
        public void sale() {
              lock.lock();  //加锁
            try {
                //业务代码
                if (number > 0) {
                    System.out.println(Thread.currentThread().getName() + "卖出了第" + (number--) + "张票,剩余" + number + "张");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock(); //解锁
            }
        }
    }

The difference between Synchronized and Lock

1.Synchronized built-in Java word Lock is a Java class

2. Synchronized cannot determine the status of acquiring the lock, Lock can determine whether the lock is acquired

3.Synchronized will automatically release the lock Lock must be manually released! If the lock is not released, deadlock

4.Synchronized thread 1 (acquisition lock, blocking) thread 2 (waiting, waiting silly); lock lock will not necessarily wait

5. Synchronized re-entrant lock, unfair that cannot be interrupted; lock re-entrant lock, unfair (you can set it yourself);

6.Synchronized is suitable for locking a small amount of code synchronization problems; lock can lock a large number of code synchronization problems;

 

 

Producer consumer problem

Synchronized version

package com.xizi.pc;
public class A {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
    }
}
class Data{
    private  int number=0;
    public synchronized void increment() throws InterruptedException {
        if (number!=0){
            // 如果不等于0  等待
            this.wait();
        }
        //等于0 +1
        number++;
        System.out.println(Thread.currentThread().getName()+"=>"+number);
        //通知其他线程 我+1完毕了
        this.notifyAll();
    }
    public synchronized void decrement() throws InterruptedException {
        if (number==0){
            // 如果等于0  等待
            this.wait();
        }
        //不等于0 -1
        number--;
        System.out.println(Thread.currentThread().getName()+"=>"+number);
        //通知其他线程 我+1完毕了
        this.notifyAll();
    }
}

Interview: Deadlock between producer and consumer of singleton pattern sorting algorithm

There are four threads ABCD

package com.xizi.pc;

public class A {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();

    }

}
class Data{
    private  int number=0;

    public synchronized void increment() throws InterruptedException {
        while (number!=0){
            // 如果不等于0  等待
            this.wait();
        }
        //等于0 +1
        number++;
        System.out.println(Thread.currentThread().getName()+"=>"+number);
        //通知其他线程 我+1完毕了
        this.notifyAll();
    }
    public synchronized void decrement() throws InterruptedException {
        while (number==0){
            // 如果等于0  等待
            this.wait();
        }
        //不等于0 -1
        number--;
        System.out.println(Thread.currentThread().getName()+"=>"+number);
        //通知其他线程 我+1完毕了
        this.notifyAll();
    }
}

 

Guess you like

Origin blog.csdn.net/weixin_45480785/article/details/105347045