本帖最后由 思维 于 2014-9-11 17:25 编辑
不会是入学面试吧!感觉有点难度啊:L- import java.util.concurrent.*;
- import java.util.*;
- class ThreadDemo{
- public static void main(String[] args){
- final int[] arr = new int[6];
- final ShareData sd = new ShareData();
- for(int i=0;i<2;i++){
- new Thread(new Runnable(){
- public void run(){
- for(int j=0;j<3;j++){
- try{
- Thread.sleep((new Random().nextInt(10)+1)*500);
- }catch(Exception e){
- e.printStackTrace();
- }
- int n = sd.increment();
- arr[n] = new Random().nextInt(10);
- System.out.println(Thread.currentThread().getName()
- +"::"+n+"::"+arr[n]);
- }
- }
- }).start();
- }
- }
- }
- //共享数据封装到一个类中
- class ShareData{
- private int i = 0;
- public synchronized int increment(){
- return i++;
- }
- }
复制代码
|