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

来源:互联网 发布:js 计算时间间隔 毫秒 编辑:程序博客网 时间:2024/05/01 07:35

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

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

以下是源代码


如有疑问或建议,请与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());}@Overridepublic 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 blocke.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;}