Java线程同步以及线程间通信(生产者与消费者)

当两个或多个线程访问同一资源时,需要以某种顺序来确保该资源在某一时刻只能被一个线程使用的方式叫做线程同步。
线程同步是为了防止同一资源同时被多个线程访问使用时造成的程序运行结果错误。
实现线程同步方法有两种,同步方法和同步代码块。
通过 synchronized关键字声明
同步方法:
访问修饰符 synchronized 返回类型 方法名(){}或
synchronized 访问修饰符 返回类型 方法名(){}
同步代码块:
synchronized(syncObject){
//所需同步代码块
}


线程间的通信方法
wait():挂起线程
notify():唤起线程
notifyAll():唤起所有被wait()方法阻塞的线程。

public class Book {
    //创建共享资源 图书类
     private String name;//图书名字
     private double price;//图书价格
     private boolean flag=true;
    public Book() {
    }
    public Book(String name, double price) {
        this.name = name;
        this.price = price;
    }
    public String getName() {
        return name;
    }
    public double getPrice() {
        return price;
    }

     public synchronized void set(String name,double price){
         if(!flag){
             try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
         }
        this.name = name;
        this.price = price;
        flag=false;
        super.notify();
     }
     public synchronized void get(){
         if(flag){
             try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
         }
         System.out.println(this.getName()+"--"+this.getPrice());
         flag=true;
         super.notify();
     }
}
 //创建一个图书馆线程 ,用来得到图书信息,销售图书
public class Library implements Runnable{
    private Book book=null;
    //标志位
    private boolean flag=false;

   public Library(Book book) {
        this.book = book;
    }

public void run(){
       //得到图书信息,销售图书  ,两本书信息交替执行,
       for(int i=1;i<=10;i++){
          if(flag){  //flag=true时执行
             this.book.set("《java》", 18);
              flag=false;
           }
          if(!flag){
               this.book.set("《MySQL》", 20);
                    flag=true;
           }
       }
   }
}
public class Client implements Runnable{
    private Book book=null;
    public Client(Book book) {
        this.book = book;
    }
    public void run(){
           //得到图书信息,购买图书
        for(int i=1;i<=10;i++){
        this.book.get();
        }
       }
}
public class test {
    //测试类
public static void main(String[] args) {
    Book book=new Book();
    Thread library =new Thread(new Library(book));
    Thread client =new Thread(new Client(book));
    library.start();
    client.start();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值