一个简单的多线程运用例子

  通过多线程对学生回家的过程进行模拟。

  在这个例子中,我们只有简单的模拟交通工具以及距离。

以下是源代码


如有疑问或建议,请与akimotolee@gmail.com 联系


/**@author Misko_Lee
 * @CreateTime 2012-01-14-21:59
 * @version 0.1
 * this is a example of thread.
 * in this project we can  find some secret of thread*/

package org.imisko.test;


import java.util.LinkedList;
import java.util.Random;

public class test{
	public static void main(String[]args){
		System.out.println("it's class begin");
		LinkedList<Student> students=new LinkedList<Student>();
		String [] names=new String[]{"jack","nonth,","jim","jay","misko"
			                      ,"frend","green","akimoto","westiu"};
		Total total=new Total(8);	
		for(int i=0;i<9;i++){
			 Random randomWay=new Random();
			 int j=randomWay.nextInt(2);
			 int way = 10;
			 switch (j) {
			case 0: way=CAR;
				
				break;
			case 1: way=FOOT;
			 break;
			 case 2: way=BICYCLE;
			default:
				break;
			}
			 Random randomDistance=new Random();
			 int distance=randomDistance.nextInt(10000)+100;
			 Student student=new Student(names[i], way, distance);
			 try{
			 WayThread wayThread=new WayThread(student, total);
			 wayThread.start();
			 }catch (Exception e) {
				// TODO: handle exception
			}
			 students.add(student);
			 if(total.isAllToHome())
				 System.out.println("all student is go to home");
		}
	}
  public static final int CAR=100;
  public static final int FOOT=20;
  public static final int BICYCLE=60;
}
/**this thread can imitate students how to go home*/
class WayThread extends Thread{
	/**way must equal to org.imisko.test.CAR or FOOT or BICYCLE*/
	public WayThread(Student s,Total total){
		student=s;
		this.total=total;
		threadSleepTime=(int) (s.getDistance()/s.getWay());
	}
	@Override
	public void run(){
		try {
			
			Thread.sleep(threadSleepTime*10);    //
			System.out.println(student.getName()+"  is goes to home!");
			total.isToHome();
		
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.err.println("is error!");
		}
		
	}
	Student student;
	Total total;
	long threadSleepTime;
}

class  Student{
	 public Student(String name,int way,float distance){
		 this.name=name;
		 this.way=way;
		 this.distance=distance;
	 }
	 public String getName(){
		 return name;
	 }
	 public int getWay(){
		 return way;
	 }
	 public float getDistance(){
		 return distance;
	 }
	 String name;
	 int way;
	 float distance;
	 
}
class Total{
	public Total(int total){
		this.total=total;
	}
	public int isToHome(){
		return total--;
	}
	public boolean isAllToHome(){
		if(total==0)
			return true;
		else 
			 return false;
	}
	
	int total;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值