Java多线程访问数组

来源:互联网 发布:闪电侠剧情介绍知乎 编辑:程序博客网 时间:2024/05/19 00:51
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<LEN)            return true;        return false;    }    public static void main(String[] args) throws InterruptedException    {        for(int i=0;i<str.length;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.length;i++)        {                td[i].start();        }        Thread.sleep(2000);        long end = System.currentTimeMillis();        System.out.println((end-start));    }   }

原创粉丝点击