开发者社区> 问答> 正文

java 线程异常问题并发性

public class BookList {
ArrayList bl =new ArrayList();
public void chunBan(){
    Book b1= new Book();
    b1.setBid(1);
    b1.setName("java");
    b1.setPrice(32.00);
    bl.add(b1);
    Book b2 = new Book();
    b2.setBid(2);
    b2.setName("c++");
    b2.setPrice(56.00);
    bl.add(b2);
}
public void chaXun(int bid) {
    for (Book book : bl) {
        if (book.getBid()==bid) {
            System.out.println(book.getName()+"\t"+book.getPrice());
        }
    }
}
public void  see() {
    for (Book book : bl) {
        System.out.println(book.getName());
    }
}
public  void update(int bid,double price) {
    for (Book book : bl) {
        if (book.getBid()==bid) {
            book.setPrice(price);
        }
    }
}
public void remove2(int bid) {
    for (Book book : bl) {
        if (book.getBid()==bid) {
            bl.remove(book);
        }
    }
}
public void jiXunChuBan(int bid,String name,double price) {
    int k=bl.size();
    Book b3 = new Book(bid,name,price);
    bl.add(k,b3);
}
public void qingKong() {
    bl.clear();
}
}
public class Book {
private int bid;
private String name;
private double price;
public Book(int bid, String name, double price) {
super();
this.bid = bid;
this.name = name;
this.price = price;
}
public Book() {
super();
}
public int getBid() {
return bid;
}
public void setBid(int bid) {
this.bid = bid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
public class BookMain {
public static void main(String[] args) {
    // TODO Auto-generated method stub
    BookList blist = new BookList();
    blist.chunBan();
    blist.see();
    blist.jiXunChuBan(3, "c", 59.00);
    blist.see();
    blist.remove2(3);
    blist.see();
}
}

展开
收起
蛮大人123 2016-03-13 17:04:26 1928 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    你线程操作同一个list等时,需要做互斥保护

    public void remove2(int bid) {
        for (Book book : bl) {
            if (book.getBid()==bid) {
                bl.remove(book);
            }
        }
    }
    用foreach方式循环遍历删除会报错
    用for的方式
    for(int i=bl.size()-1;i>=0;i--){
        Book book = (Book)bl.get(i);
        if (book.getBid()==bid) {
                bl.remove(book);
            }
    }
    2019-07-17 19:02:53
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
多IO线程优化版 立即下载