- package com.cai.test;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Random;
- public class ThreadTest extends Thread {
- // 数组share索引
- public int index = 0;
- public static void main(String[] args) throws Exception {
- // share用于保存2个线程添加的数据
- String[] share = new String[6];
- ThreadTest tt = new ThreadTest();
- Thread t1 = new Thread(new AddData(share, tt), "线程A");
- Thread t2 = new Thread(new AddData(share, tt), "线程B");
- t1.start();
- t2.start();
- // 当2个线程执行完,才执行下面的main线程程序
- t1.join();
- t2.join();
- // 遍历share保存的数据
- for (int i = 0; i < share.length; i++) {
- System.out.println(Thread.currentThread().getName() + "--"
- + share[i]);
- }
- }
- }
- class AddData implements Runnable {
- private String[] share;
- private ThreadTest tt;
- public AddData(String[] share, ThreadTest tt) {
- this.share = share;
- this.tt = tt;
- }
- @Override
- public void run() {
- String[] data = { "第一个数据", "第二个数据", "第三个数据" };
- synchronized (share) {
- for (int i = 0; i < data.length; i++) {
- try {
- Thread.sleep((new Random().nextInt(10) + 1) * 10);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- this.share[tt.index++] = Thread.currentThread().getName() + ":"
- + data[i];
- }
- }
- }
- }
复制代码 |