package com.xgd.thread.test;
/**
* Package: com.xgd.thread.test
*
* File: ThroughCave.java
*
* Author: jiangpan Date: 2015年9月21日
*
* Copyright @ 2015 Corpration Name
*
*/
public class ThroughCave {
private String[] name;
public ThroughCave() {
//在构造方法中初始化一个包含10个人名的String数组
String[] name = {"张三","李四","王五","马六","牛七","王八","小明","小红","小花","小雷"};
this.name = name;
}
//输出人名的方法,同步化synchronized
public synchronized void PrintName(String name){
//延迟5s,模拟过山洞的时间为5s
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name);
}
//将10个人名分给10个线程,模拟10个人
public void SendAllNames(){
for (int i = 0; i < name.length; i++) {
GetNameThread gt = new GetNameThread(this, name[i]);
gt.start();
}
}
public static void main(String[] args){
ThroughCave tc = new ThroughCave();
tc.SendAllNames();
}
}
线程类:
package com.xgd.thread.test;
/**
* Package: com.xgd.thread.test
*
* File: GetNameThread.java
*
* Author: jiangpan Date: 2015年9月21日
*
* Copyright @ 2015 Corpration Name
*
*/
public class GetNameThread extends Thread{
private ThroughCave tcave;
private String name;
//初始化线程的时候,获得回调类对象和人名
public GetNameThread(ThroughCave tcave,String name) {
this.tcave = tcave;
this.name = name;
}
public void run(){
//输出人名,模拟过山洞
tcave.PrintName(name);
}
}