public static void main(String[] args){
Map<Integer, Object>tables = new Hashtable<Integer, Object>()
Thread add = new Thread(new ThreadAdd(tables))
Thread del = new Thread(new ThreadDel(tables))
Thread count = new Thread(new ThreadCount(tables))
//启动线程
add.start()
del.start()
count.start()
}
/**
*/
private static class ThreadAdd implements Runnable{
private Map<Integer, Object>table
public ThreadAdd(Map<Integer, Object>tables){
this.table=tables
}
public void run() {
// TODO Auto-generated method stub
for(int i=0i<10i++){
table.put(i, new Object())
System.out.println("添加对象,序号为:"+i)
}
}
}
/**
*删除对象线程
*/
private static class ThreadDel implements Runnable{
private Map<Integer, Object>table
public ThreadDel(Map<Integer, Object>table){
this.table=table
}
public void run() {
// TODO Auto-generated method stub
for(int i=0i<10i++){
try {
Thread.sleep(100)
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
table.remove(i)
System.out.println("移除对象,序号为:"+i)
}
}
}
/**
*统计线程
*/
private static class ThreadCount implements Runnable{
private Map<Integer, Object>table
public ThreadCount(Map<Integer, Object>table){
this.table=table
}
public void run() {
// TODO Auto-generated method stub
for(int i=0i<10i++){
try {
Thread.sleep(50)
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
System.out.println("当前队列还剩"+table.size()+"个对象")
}
}
}
}
这是我的写的demo,不知道符合不符合你的意思,大家共同交流共同进步。
思路:通过两轮循环控制,先获取q1,q2中较短的长度lenMin,来进行第一轮循环i<lenMin,
将q1,q2的值都添加到q3中
i++
继续利用i的值,然后将剩下的那个list再通过一个循环添加到q3中。
i<lenMax,
添加
i++
详细代码:
@Test
public void arrayListAdd(){
ArrayList q1 = new ArrayList()
ArrayList q2 = new ArrayList()
ArrayList q3 = new ArrayList()
String str1 = "abcdefdef"
String str2 = "12345"
int len1= str1.length()
int len2= str2.length()
for(char c:str1.toCharArray())
q1.add(c)
for(char c:str2.toCharArray())
q2.add(c)
int max = len1>len2?len1:len2
int min = len1<len2?len1:len2
//System.out.println(max+" "+min+q1+q2)
int i=0
while(i<min){
q3.add(q1.get(i))
q3.add(q2.get(i))
i++
}
while(i<max){
if(len1 == max){
q3.add(q1.get(i))
}else{
q3.add(q2.get(i))
}
i++
}
System.out.println(q3)
}
输出结果:[a, 1, b, 2, c, 3, d, 4, e, 5, f, d, e, f]
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)