线程安全问题

2018-03-09  本文已影响0人  QinRenMin
synchronoized(对象)
{
    需要被同步的代码块;
}

同步的好处:解决了线程安全问题;
同步的弊端:相对降低了效率,因为同步外的线程都会判断同步锁;
同步的前提:必须有多个线程使用同一个同步锁。

class TDemo implements Runnable {
    
    int i = 10;
    public void run()
    {
        while(true){
            if(i > 0)
            {
                try
                {
                    Thread.sleep(10);
                }
                catch(InterruptedException e)
                {
                }
                System.out.println(Thread.currentThread().getName()+"--"+i--);
            
            }
        }
    }
}
public class TongBu {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TDemo d = new TDemo();
        Thread t1 = new Thread(d);
        Thread t2 = new Thread(d);
        Thread t3 = new Thread(d);
        t1.start();
        t2.start();
        t3.start();
    }

}

image.png

以上代码会出现线程安全问题

解决如下:

class TDemo implements Runnable {
    
    int i = 10;
    public void run()
    {
        while(true){
            synchronized (this){
                if(i > 0)
                {
                    try
                    {
                        Thread.sleep(10);
                    }
                    catch(InterruptedException e)
                    {
                    }
                    System.out.println(Thread.currentThread().getName()+"--"+i--);
                
                }
            }
            }
            
    }
}
public class TongBu {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TDemo d = new TDemo();
        Thread t1 = new Thread(d);
        Thread t2 = new Thread(d);
        Thread t3 = new Thread(d);
        t1.start();
        t2.start();
        t3.start();
    }

}
image.png
上一篇 下一篇

猜你喜欢

热点阅读