线程知识学习 四 ——并发

前几篇博客写了线程基础,这篇博客,我们开始了解线程同步的知识。

线程同步使用的方案

线程并发?

简单的说,就是多个线程同时要访问同同一块程序代码。那么我们为什么总是在讨论多线程呢?还总是和线程安全问题一起出现?

其实线程安全是:多个线程,同时操作了一个对象的成员变量,这样造成一个线程的工作没有做完,结果正在使用的数据发生了变化,这就是不合理的,所以线程安全,是和对象的成员变量连在一起的。那么多线程编程或者并发编程要做的就是:保证好这个类被实例化后成对象后,可能操作这个对象的成员变量的值的代码块同时只能有一个线程在操作,这里的代码块的数量是不定的,一个,两个,多个都是有可能的。

还是老规矩,我们先来看看实现线程同步的都有哪些东东。

这里写图片描述

同步——synchronized

特定对象访问

当两个并发线程访问同一个对象中的这个synchronized(this)同步代码块时,一个时间内只能有一个线程得到执行。另一个线程必须等待当前线程执行完这个代码块以后才能执行该代码块。但是,当一个线程访问该对象的一个synchronized(this)同步代码块时,另一个线程仍然可以访问该object中的非synchronized(this)同步代码块。

使用场景:A用户的账户上有1000元,在同一天,A 和其老婆在没有商量的情况下,都去银行办理业务。A存款1000,A老婆 取款 500;A先开始办理的,但是在A读取银行余额后,A老婆介入了,然后在A存款之前,A老婆办理完毕,然后,A存款成功。正常的情况下,A的账户上应该有1500元,但是结果却告诉我们,有2000元,是不是很爽。这就是 两个线程同时操作一个变量导致的,所以,这两个方法不可以同时被执行。我们需要互斥执行。

Synchronized 的实现原理:将代码块使用synchronized修饰,同时只有一个线程访问这块代码;
同步是针对对象来说的,需要有对象的参与才能保证同步;
性能低,所以同步的代码块要小,

图下如下。
这里写图片描述

同步代码块的写法如下,注意对象的传入this

synchronized(this) {  
               for (int i = 0; i < 5; i++) {  
                    System.out.println(Thread.currentThread().getName() + " synchronized loop " + i);  
               }  
          }

依赖属性

当使用synchronized关键字来保护代码块时,必须把对象引用作为传入参数。通常情况下,使用this关键字来引用执行方法所属的对象,也可以使用其他的对象对其进行引用。 一般来说,这些对象就是为这个目的而创建的。例如,在类中有两个非依赖属性,它们被 多个线程共享,你必须同步每一个变量的访问,但是同一时刻只允许一个线程访问一个属性变量,其他某个线程访问另一个属性变量。
经典案例:通过范例学习实现电影院售票场景的编程。这个范例模拟了有两个屏幕和两个售票处的电影院,一个售票处卖出的一张票,只能用于其中一个电影院,不能同时用于两个电影院,因此每个电影院的剩余票数是独立的属性。

package com.packtpub.java7.concurrency.chapter2.recipe2.core;

import com.packtpub.java7.concurrency.chapter2.recipe2.task.Cinema;
import com.packtpub.java7.concurrency.chapter2.recipe2.task.TicketOffice1;
import com.packtpub.java7.concurrency.chapter2.recipe2.task.TicketOffice2;

/**
 * Core class of the example. Creates a cinema and two threads for
 * the ticket office. Run the threads to analyze the results obtained
 *
 */
public class Main {

    /**
     * Main method of the example
     * @param args
     */
    public static void main(String[] args) {
        // Creates a Cinema
        Cinema cinema=new Cinema();

        // Creates a TicketOffice1 and a Thread to run it
        TicketOffice1 ticketOffice1=new TicketOffice1(cinema);
        Thread thread1=new Thread(ticketOffice1,"TicketOffice1");

        // Creates a TicketOffice2 and a Thread to run it
        TicketOffice2 ticketOffice2=new TicketOffice2(cinema);
        Thread thread2=new Thread(ticketOffice2,"TicketOffice2");

        // Starts the threads
        thread1.start();
        thread2.start();

        try {
            // Waits for the finalization of the threads
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Print the vacancies in the cinemas
        System.out.printf("Room 1 Vacancies: %d\n",cinema.getVacanciesCinema1());
        System.out.printf("Room 2 Vacancies: %d\n",cinema.getVacanciesCinema2());
    }

}
package com.packtpub.java7.concurrency.chapter2.recipe2.task;

public class Cinema {

    /**
     * This two variables store the vacancies in two cinemas
     */
    private long vacanciesCinema1;
    private long vacanciesCinema2;

    /**
     * Two objects for the synchronization. ControlCinema1 synchronizes the
     * access to the vacancesCinema1 attribute and controlCinema2 synchronizes
     * the access to the vacanciesCinema2 attribute.
     */
    private final Object controlCinema1, controlCinema2;

    /**
     * Constructor of the class. Initializes the objects
     */
    public Cinema(){
        controlCinema1=new Object();
        controlCinema2=new Object();
        vacanciesCinema1=20;
        vacanciesCinema2=20;
    }

    /**
     * This method implements the operation of sell tickets for the cinema 1
     * @param number number of tickets sold
     * @return true if the tickets are sold, false if there is no vacancies
     */
    public boolean sellTickets1 (int number) {
        synchronized (controlCinema1) {
            if (number<vacanciesCinema1) {
                vacanciesCinema1-=number;
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * This method implements the operation of sell tickets for the cinema 2
     * @param number number of tickets sold
     * @return true if the tickets are sold, false if there is no vacancies
     */
    public boolean sellTickets2 (int number){
        synchronized (controlCinema2) {
            if (number<vacanciesCinema2) {
                vacanciesCinema2-=number;
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * This method implements the operation of return tickets for the cinema 1
     * @param number number of the tickets returned
     * @return true
     */
    public boolean returnTickets1 (int number) {
        synchronized (controlCinema1) {
            vacanciesCinema1+=number;
            return true;
        }
    }

    /**
     * This method implements the operation of return tickets for the cinema 1
     * @param number number of the tickets returned
     * @return true
     */
    public boolean returnTickets2 (int number) {
        synchronized (controlCinema2) {
            vacanciesCinema2+=number;
            return true;
        }
    }

    /**
     * Return the vacancies in the cinema 1
     * @return the vacancies in the cinema 1
     */
    public long getVacanciesCinema1() {
        return vacanciesCinema1;
    }

    /**
     * Return the vacancies in the cinema 2
     * @return the vacancies in the cinema 2
     */
    public long getVacanciesCinema2() {
        return vacanciesCinema2;
    }

}
package com.packtpub.java7.concurrency.chapter2.recipe2.task;

/**
 * This class simulates a ticket office. It sell or return tickets
 * for the two cinemas
 *
 */
public class TicketOffice1 implements Runnable {

    /**
     * The cinema 
     */
    private Cinema cinema;

    /**
     * Constructor of the class
     * @param cinema the cinema
     */
    public TicketOffice1 (Cinema cinema) {
        this.cinema=cinema;
    }

    /**
     * Core method of this ticket office. Simulates selling and returning tickets
     */
    @Override
    public void run() {
        cinema.sellTickets1(3);
        cinema.sellTickets1(2);
        cinema.sellTickets2(2);
        cinema.returnTickets1(3);
        cinema.sellTickets1(5);
        cinema.sellTickets2(2);
        cinema.sellTickets2(2);
        cinema.sellTickets2(2);
    }

}
package com.packtpub.java7.concurrency.chapter2.recipe2.task;

/**
 * This class simulates a ticket office. It sell or return tickets
 * for the two cinemas
 *
 */
public class TicketOffice2 implements Runnable {

    /**
     * The cinema 
     */
    private Cinema cinema;

    /**
     * Constructor of the class
     * @param cinema the cinema
     */
    public TicketOffice2(Cinema cinema){
        this.cinema=cinema;
    }

    /**
     * Core method of this ticket office. Simulates selling and returning tickets
     */
    @Override
    public void run() {
        cinema.sellTickets2(2);
        cinema.sellTickets2(4);
        cinema.sellTickets1(2);
        cinema.sellTickets1(1);
        cinema.returnTickets2(2);
        cinema.sellTickets1(3);
        cinema.sellTickets2(2);
        cinema.sellTickets1(2);
    }

}

这个例子使用了一个对象来控制对vacanciesCinema1属性的访问,所以同一时间只有一个线程能够修改这个属性:使用了另一个对象来控制vacanciesCinema2属性的访问,所以同一时间只有一个线程能够修改这个属性。但是,这个例子允许同时运行两个线 程:一个修改vacancesCinemal属性,另一个修改vacanciesCinema2属性。

下篇博客:我们介绍解决并发的其他方案,有JDK提供的,有第三饭的辅助类库。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值