Java learning summary: 28

Thread synchronization and deadlock

In program development, all programs are executed by the main method, and the main method itself belongs to a main thread, so the new thread object created by the main method is a child thread.
The use of sub-threads can perform asynchronous operation processing, so that other operations can be performed without affecting the operation of the main thread. The execution speed of the program not only becomes faster, but the operation does not cause too much delay.

Synchronous operation

The so-called synchronous operation means that multiple operations in a code can only be performed by one thread in the same time period, and other threads can wait for this thread to complete before continuing execution.
Synchronized operation
In Java, you can use the synchronized keyword to achieve thread synchronization. This keyword can be used in the following two ways:
1. Synchronized code block: a code block wrapped with synchronized, but you need to specify the synchronization object, generally set to this;
2 . Synchronization method: Use the method defined by synchronized.

Example: Observe the synchronized code block

package Project.Study.Multithreading;

class MyThread7 implements Runnable{
    private int ticket=10;			//一共有10张票
    @Override
    public void run(){
        for (int x=0;x<10;x++){
            synchronized(this){		//定义同步代码块
                if(this.ticket>0){	//判断当前是否还有剩余票
                    try {
                        Thread.sleep(100);	//休眠1s,模拟延迟
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+",卖票,ticket="+this.ticket--);
                }
            }
        }
    }

}
public class Test7 {
    public static void main(String [] args){
        MyThread7 mt=new MyThread7();
        new Thread(mt,"票贩子A").start();		//启动多线程
        new Thread(mt,"票贩子B").start();
        new Thread(mt,"票贩子C").start();
        new Thread(mt,"票贩子D").start();
    }
}
//结果:
//票贩子A,卖票,ticket=10
//票贩子A,卖票,ticket=9
//票贩子A,卖票,ticket=8
//票贩子A,卖票,ticket=7
//票贩子A,卖票,ticket=6
//票贩子A,卖票,ticket=5
//票贩子A,卖票,ticket=4
//票贩子A,卖票,ticket=3
//票贩子A,卖票,ticket=2
//票贩子A,卖票,ticket=1

Example: Solve the problem using the synchronization method

package Project.Study.Multithreading;

class MyThread8 implements Runnable{
    private int ticket=10;          //一共有10张票
    @Override
    public void run(){
        for (int x=0;x<20;x++){
            this.sale();            //卖票操作
        }
    }
    public synchronized void sale(){//同步方法
        if (this.ticket>0){         //判断当前是否还有剩余票
            try{
                Thread.sleep(100);//休眠1s,模拟延迟
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+",卖票,ticket="+this.ticket--);
        }
    }
}
public class Test8 {
    public static void main(String []args){
        MyThread8 mt=new MyThread8();
        new Thread(mt,"票贩子A").start();//启动多线程
        new Thread(mt,"票贩子B").start();
        new Thread(mt,"票贩子C").start();
        new Thread(mt,"票贩子D").start();
    }
}
//结果:
//票贩子A,卖票,ticket=10
//票贩子A,卖票,ticket=9
//票贩子A,卖票,ticket=8
//票贩子A,卖票,ticket=7
//票贩子A,卖票,ticket=6
//票贩子A,卖票,ticket=5
//票贩子A,卖票,ticket=4
//票贩子A,卖票,ticket=3
//票贩子A,卖票,ticket=2
//票贩子A,卖票,ticket=1

Note:
1. Methods, static, native, and synchronized cannot be declared with "abstract" at the same time.
2. When a thread enters a synchronized method of an object, other threads cannot access other methods of this object.
3. Synchronized code performance will be lower, but the data security will be high (thread security is high); asynchronous code is often more efficient, but thread security is lower (most of the data is shared data, that is Used by other threads).

Deadlock

Too many simultaneous operations may cause a deadlock problem, causing the program to enter a stalled state. The so-called deadlock means that two threads are waiting for each other to complete first, resulting in the stagnation of the program . Generally, the deadlock of the program occurs when the program is running.

Example: Program deadlock operation

package Project.Study.Multithreading;

class A{
    public synchronized void say(B b){
        System.out.println("A先生说:把你的笔记本给我,我给你笔,否则不给!");
        b.get();
    }
    public synchronized void get(){
        System.out.println("A先生:得到了笔记本,付出了笔,还是什么都干不了!");
    }
}
class B{
    public synchronized void say(A a){
        System.out.println("B先生说:把你的笔给我,我给你笔记本,否则不给!");
        a.get();
    }
    public synchronized void get(){
        System.out.println("B先生:得到了笔,付出了笔记本,还是什么都干不了");
    }
}
public class Test9 implements Runnable{
    private static A a=new A();                 //定义类对象
    private static B b=new B();
    public static void main(String[]args){
        new Test9();                            //实例化本类对象
    }
    public Test9(){                             //构造方法
        new Thread(this).start();        //启动线程
        b.say(a);                               //互相引用
    }
    @Override
    public void run(){
        a.say(b);                               //互相引用
    }
}
//结果:
//B先生说:把你的笔给我,我给你笔记本,否则不给!
//A先生说:把你的笔记本给我,我给你笔,否则不给!
//(程序将不会再向下执行,并且不会退出,此为死锁情况出现)

In the above program, because both classes use synchronous method definitions, it will cause the a object to wait for the b object to complete its execution, and the b object to wait for the a object to complete its execution, which will cause a deadlock.

49 original articles published · Liked 25 · Visits 1520

Guess you like

Origin blog.csdn.net/weixin_45784666/article/details/105056353