java multithreading safety issues

Program by selling tickets or ticket booking identify problems repeat negative

class Ticket implements Runnable{
    private int tick=100;
    @Override
    public void run() {
        while (true){
            if (tick>0){
                try {
                    Thread.sleep ( 10); // plurality of threads waiting, then execution right acquired 
                } the 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 in operation the same shared data, only one thread to execute multiple statements part, has not been performed, another thread to perform involved, leading to erroneous data sharing.

Solution: share data about many of the operating statement, only to a thread executed, in execution, other threads can not participate in the implementation.

Java multi-thread-safe solution: synchronized 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();
    }
}

Inside object ( Object.class ) If the lock, thread holding the lock can be performed in sync,

No thread holding the lock even get the cpu executive power, can not get in, because there is no lock acquisition.

Synchronous premise:

1 or above must have two threads.

2. Multiple threads must use the same lock.

We must ensure that only one thread synchronization in operation.

Benefits: to solve the security problems of multithreading.

Drawbacks: multiple threads need to determine the lock, the more consumption of resources,

 

Guess you like

Origin www.cnblogs.com/hongxiao2020/p/12588925.html