Home > Java > javaTutorial > body text

Detailed explanation of thread safety issues in Java

黄舟
Release: 2017-08-09 09:15:47
Original
1670 people have browsed it

Give a problem as follows:

The solution is as follows:

public class Demo_5 {

    public static void main(String[] args) {
        //创建一个窗口
        TicketWindow tw1=new TicketWindow();

        //使用三个线程同时启动
        Thread t1=new Thread(tw1);
        Thread t2=new Thread(tw1);
        Thread t3=new Thread(tw1);
        
        t1.start();
        t2.start();
        t3.start();
    }

}

//售票窗口类
class TicketWindow implements Runnable{
    private int nums=2000;                         //一共2000张票

    @Override
    public void run() {
        while(true){        
        
                if(nums>0){                        //先判断是否还有票
                    //Thread.currentThread().getName()得到当前线程的名字
                    System.out.println(Thread.currentThread().getName()+"在售出第"+nums+"张票");    //显示售票信息
                
                    //出票的速度是一秒出一张
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                
                    nums--;
                }else{
                    break;                            //售票结束
                }
                
      }        
  }    
}
Copy after login

Execute this code and find the problem, that is, the same ticket number may be For sale at multiple ticket windows, the troublesome code is the if else statement block.

The solution is to use synchronized(Object){the code you want to synchronize} in the code segment that needs to be synchronized.

The modified code is as follows:

public class Demo_5 {

    public static void main(String[] args) {
        //创建一个窗口
        TicketWindow tw1=new TicketWindow();

        //使用三个线程同时启动
        Thread t1=new Thread(tw1);
        Thread t2=new Thread(tw1);
        Thread t3=new Thread(tw1);
        
        t1.start();
        t2.start();
        t3.start();
    }

}

//售票窗口类
class TicketWindow implements Runnable{
    private int nums=2000;                         //一共2000张票

    @Override
    public void run() {
        while(true){        
            //认为if else这段代码要保证其原子性(同步代码块)
            synchronized (this) {
        
                if(nums>0){                             //先判断是否还有票
                    //Thread.currentThread().getName()得到当前线程的名字
                    System.out.println(Thread.currentThread().getName()+"在售出第"+nums+"张票");    //显示售票信息
                
                    //出票的速度是一秒出一张
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                
                    nums--;
                }else{
                    break;                            //售票结束
                }
                
            }
        }
    }    
}
Copy after login

Execute this code and find that the ticket issuance is normal.

Thread 1 is executing code that needs to be synchronized. Threads 2, 3, 4... are blocked and put into the thread waiting pool, just like someone closing (locking) the door before going to the toilet. Come out (unlock) after you're done, and then others can continue to use it.

The above is the detailed content of Detailed explanation of thread safety issues in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template