[Java] 纯文本查看 复制代码
package com.jonn.demo;
import java.util.*;
import java.util.concurrent.locks.*;
class Person implements Runnable
{
private List<Person> person=ArrayListDemo.getIntance();
private Lock lock=new ReentrantLock();
private Condition condi_addEl=lock.newCondition();
private Condition condi_delEl=lock.newCondition();
private static boolean flag=false;
private String name;
private int age;
Person(String name,int age){
this.setPersonInfo(name,age);
}
public void setPersonInfo(String name,int age){
this.name=name;
this.age=age;
}
public String getPersonInfo(){
return this.name+","+this.age;
}
public String toString(){
return this.getPersonInfo();
}
public void addElements(Person p) throws InterruptedException{
lock.lock();
try{
if(flag)
condi_addEl.await();
person.add(p);
System.out.println(Thread.currentThread().getName()+"---添加元素---"+p);
ArrayListDemo.printList(person);
flag=true;
condi_delEl.signal();
}
finally{
lock.unlock();
}
}
public void delElements(Person p) throws InterruptedException{
lock.lock();
try{
if(!flag)
condi_delEl.await();
person.remove(p);
System.out.println(Thread.currentThread().getName()+"---删除元素---"+p);
ArrayListDemo.printList(person);
flag=false;
condi_addEl.signal();
}
finally{
lock.unlock();
}
}
public void run(){
int i=0;
while(flag){
if(i==0)
try{
addElements(new Person("gao",24));
}catch(InterruptedException e){
changeFlag();
}
else
try{
delElements(null);
}catch(InterruptedException e)
{
changeFlag();
}
i=(i+1)%2;
}
}
public static boolean changeFlag(){
return flag=false;
}
};
class ArrayListDemo
{
private static List<Person> person=null;
private ArrayListDemo(){
}
public static List<Person> getIntance(){
if(person==null){
if(person==null)
person=Collections.synchronizedList(new ArrayList<Person>());
}
return person;
}
protected static void printList(List<?> e){
Iterator<?> iter=e.iterator();
while(iter.hasNext()){
System.out.println(iter.next());
}
}
private static void printInfo(List<Person> e){
for(Iterator iter=e.iterator();iter.hasNext();){
Person p=(Person)iter.next();
System.out.println(p);
}
}
public static void main(String[] args)
{
Person[] p={
new Person("张三",22),
new Person("李四",23),
new Person("王五",22)
};
person.addAll(Arrays.asList(p));
person.add(1,new Person("六路",24));
Thread t1=new Thread(new Person("lisi",25));
Thread t2=new Thread(new Person("kk",23));
t1.setDaemon(true);
t2.setDaemon(true);
t1.start(); // 线程启动后,执行run()方法无效,无结果,求改代码....
t2.start();
int x=0;
boolean flag=true;
while(flag){
if(x==50){
flag=false;
}
x++;
System.out.println(Thread.currentThread().getName()+"---"+x);
}
}
};