本帖最后由 wyasln 于 2015-12-6 13:07 编辑
练习练习准备面试了
原需求是开启两线程向一个数组中各写入三个元素,我稍改了下可以为每个线程指定要写入多少个数据,就没用数组了。
开始循环部分少写了i++,我还奇怪程序已跑起不停了,电脑风扇也开始呼呼了
下面是代码
package com.xy;
import java.util.ArrayList;
public class MyTest04 {
public static void main(String[] args) {
MyArray ma = MyArray.getInstance();
Thread t1 = new Thread(new SetValue(ma,8));
Thread t2 = new Thread(new SetValue(ma,8));
t1.start();
t2.start();
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
ma.print();
}
}
class SetValue implements Runnable
{
private MyArray ma;
private int num;
public SetValue(MyArray ma,int num)
{
this.ma = ma;
this.num = num;
}
@Override
public void run() {
int i = 0;
int val = 0;
while(i<num)
{
val = (int)(Math.random()*100 + 1);
ma.add(val);
i++;
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyArray
{
private ArrayList<Integer> list = new ArrayList<Integer>();
private static MyArray ma = new MyArray();
private MyArray(){};
public static MyArray getInstance(){
return ma;
}
public synchronized boolean add(int val){
return list.add(val);
}
public void print()
{
System.out.println("数组中共有"+list.size()+"个元素:");
for(int i=0;i<list.size();i++)
{
System.out.print(list.get(i)+" ");
}
System.out.print("\n");
}
}结果:
66 48 60 79 92 67 75 22 68 32 6 65 30 69 67 77
|
|