Java多線程訪問數組

來源:互聯網
上載者:User
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));    }   }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.