public class Test_Runnable implements Runnable{
private String name;
private static int next = 0;
private static int LEN = 10000;
private final static int NUM = 5;
private static String str[] = new String[LEN];
public Test_Runnable(String name) {
super();
this.name = name;
}
public Test_Runnable() {
super();
// TODO Auto-generated constructor stub
}
public static void visit(String name) throws InterruptedException
{
while(hasNext())
{
System.out.println(str[getNext()]+" "+name);
Thread.sleep(1);
}
}
public void run() {
for(int i=0;i<4;i++)
{
try {
visit(this.name);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//下一次应该访问的数组元素的索引
public synchronized static int getNext()
{
next++;
return next-1;
}
//判断有没有访问完毕
public static boolean hasNext()
{
if(next
return true;
return false;
}
public static void main(String[] args) throws InterruptedException
{
for(int i=0;i
{
str[i] = new String("string " + i);
}
Thread.sleep(1000);
//建立十个线程
Test_Runnable tr[] = new Test_Runnable[NUM];
Thread td[] = new Thread[NUM];
for(int i = 0;i < tr.length; i++)
{
tr[i] = new Test_Runnable("thread" + i);
td[i] = new Thread(tr[i]);
}
long start = System.currentTimeMillis();
Thread.sleep(1000);
//线程开始执行任务
for(int i=0;i
{
td[i].start();
}
Thread.sleep(2000);
long end = System.currentTimeMillis();
System.out.println((end-start));
}
}