Java使用synchronized实现多线程操作list<1>
来源:互联网 发布:java socket通信协议 编辑:程序博客网 时间:2024/05/17 08:26
Java的多线程实现方式有两种,一种是继承Thread类,一中是实现Runnable接口,这两种都要重写run方法,因为在run方法中存放的是要在多线程执行的代码,使用synchronized时要绑定一个对象,对于存在多个线程竞争的程序时就需要多个程序使用的是同一个锁资源,否则无法实现同步,具体的代码如下
下面以经典的生产者、消费者为例
生产者线程:
public class Producer implements Runnable {
private LinkedList<Student> mylist=new LinkedList<Student>();
private int MAX=100;
public Producer(){
}
public Producer(LinkedList<Student> list){
this.mylist=list;
}
public void run() {
// TODO Auto-generated method stub
while(true){
synchronized(mylist){
while(mylist.size()>MAX){
System.out.println(Thread.currentThread().getName()+ "仓库已满");
try {
mylist.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Student stu=new Student("张三", 20);
if(mylist.add(stu)){
System.out.println("生产了一个"+stu.getName());
mylist.notifyAll();
}
}
}
}
}
消费者线程:
public class Consumer implements Runnable{
private LinkedList<Student> mylist=new LinkedList<Student>();
public Consumer(){
}
public Consumer(LinkedList<Student> list){
this.mylist=list;
}
public void run() {
// TODO Auto-generated method stub
while(true){
synchronized (mylist) {
while(mylist.size()==0){
System.out.println(Thread.currentThread().getName()+ "仓库为空");
try {
mylist.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Student stu=mylist.removeLast();
System.out.println("消费了一个"+stu.getAge());
mylist.notifyAll();
}
}
}
}
实现多线程:
public class MoreThread {
private static LinkedList<Student> mylist=new LinkedList<Student>();
public static void main(String[] args) {
Thread t1=new Thread(new Producer(mylist));
Thread t2=new Thread(new Consumer(mylist));
Thread t3=new Thread(new Producer(mylist));
Thread t4=new Thread(new Consumer(mylist));
t1.setName("生产者1---");
t3.setName("生产者2---");
t2.setName("消费者1---");
t4.setName("消费者2---");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
- Java使用synchronized实现多线程操作list<1>
- 使用synchronized和volatile实现Java多线程同步
- Java多线程同步 synchronized使用
- java 多线程操作List,已经做了同步synchronized,还会有ConcurrentModificationException,知道为什么吗?
- Java多线程同步Synchronized使用分析
- Java多线程同步Synchronized使用分析
- Java多线程同步Synchronized使用分析
- Java多线程同步Synchronized使用分析
- Java中多线程Synchronized使用技巧
- java多线程中使用synchronized说明
- 【Java】多线程同步Synchronized使用分析
- Java 多线程中使用synchronized及解锁
- Java多线程同步Synchronized使用分析
- Java多线程同步 synchronized 关键字的使用
- Java多线程同步Synchronized使用分析
- Java多线程之synchronized的使用技巧
- Java多线程笔记二(synchronized的使用以及实现原理)
- 多线程synchronized使用
- Cachē的定时任务Tasks 配置方法
- IOS Notes (二)
- Oracle 11g AMM与ASMM切换
- python 爬虫抓取心得分享
- NOJ1102 黑白图像
- Java使用synchronized实现多线程操作list<1>
- 回调函数
- 按地名字符,给地名排序。
- SEO两级分化严重,你是大神还是菜鸟?
- YUV格式详解
- 幂的探究 快速幂 质因数分解 最小乘法次数
- RevitAPI: 如何获取RevitLinkInstance链接模型的位置?
- 学密码学一定得学程序
- Hotspot虚拟机对象探秘