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();

}


}


0 0
原创粉丝点击