.总结多线程同步的两大方式synchronized与lock的使用。

线程同步处理: 同步指的是所有的线程不是一起进入到方法里面执行,而是按照顺序一个一个来

Synchornized处理同步问题和Lock锁处理同步问题

Synchornize处理同步问题有两种方法:

1.同步代码块

2.同步方法

实现:1.

package www.xianchengtongbu;

class MyThread implements Runnable {
    private Integer tickets = 10;

    @Override
    public void run() {
        synchronized (this) {//同步代码块,锁定进入此代码块的对象,一次只能进入一个线程
                            //为逻辑行为上锁
            while (tickets > 0) {//还有票
                try {
                    Thread.sleep(200);//模拟网络延迟
                } catch (InterruptedException e) {
                    
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "还剩:" + tickets-- + "张票");
            }
        }

    }

}

public class Synchronized_TongBu {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        Thread thread = new Thread(myThread, "黄牛A");
        Thread thread1 = new Thread(myThread, "黄牛B");
        Thread thread2 = new Thread(myThread, "黄牛C");
        thread.start();
        thread1.start();
        thread2.start();

    }

}
实现: 2.同步方法:

package www.xianchengtongbu;

class MyTest implements Runnable{
    private int tickets=10;
    @Override
    public void run() {
        for(int i=tickets;i>0;i--) {
            this.sale();
        }
    }
    public synchronized void sale() {  //同步方法
        if(this.tickets>0) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"还剩:"+tickets--+"张票");
        }
    }
    
}

public class Synchronized_TongbuFangFa {
    public static void main(String[] args) {
        MyTest myTest=new MyTest();
        Thread thread=new Thread(myTest,"黄牛A");
        Thread thread2=new Thread(myTest,"黄牛B");
        Thread thread3=new Thread(myTest,"黄牛C");
        thread.start();
        thread2.start();
        thread3.start();
        
    }

}

JDK1.5提供的lock锁(了解就好)


 

猜你喜欢

转载自blog.csdn.net/sd116460/article/details/81239850