java multithreading security

Through the ticket selling process, it is found that the ticket is sold repeatedly or the number of tickets sold is negative

class Ticket implements Runnable{
    private int tick=100;
    @Override
    public void run() {
        while (true){
            if (tick>0){
                try {
                    Thread.sleep(10);//Multiple threads wait and get execution rights
                }catch (InterruptedException e){
                }

                System.out.println(Thread.currentThread().getName()+"...sale:"+tick--);
            }
        }
    }
}
public class Demo {
    public static void main(String[] args) {
        Ticket t = new Ticket();
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
        t1.start();
        t2.start();
    }
}

When multiple statements operate on the same shared data, one thread only executes a part of multiple statements, which has not finished executing. Another thread participates in the execution, resulting in the error of shared data.

Solution: for statements with multiple operations sharing data, only one thread can complete the execution. During the execution, other threads cannot participate in the execution.

Java multithreading security solution: synchronous code block

class Ticket implements Runnable{
    private int tick=100;
    @Override
    public void run() {
        while (true){
            synchronized (Object.class){
                if (tick>0){
                    try {
                        Thread.sleep(10);
                    }catch (InterruptedException e){
                    }

                    System.out.println(Thread.currentThread().getName()+"...sale:"+tick--);
                }
            }
        }
    }
}
public class Demo {
    public static void main(String[] args) {
        Ticket t = new Ticket();
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
        t1.start();
        t2.start();
    }
}

If the object. Class is locked, the thread holding the lock can execute in synchronization,

A thread without a lock can not enter even if it acquires the execution right of the cpu, because it does not acquire a lock.

Premise of synchronization:

1. There must be two or more threads.

2. Multiple threads must use the same lock.

You must ensure that only one thread is running in the synchronization.

Benefit: solves the security problem of multithreading.

Disadvantages: multiple threads need to judge locks, which consumes resources,

Keywords: Java

Added by randalusa on Sat, 28 Mar 2020 16:05:59 +0200