使用Thread类创建两个模拟猫和狗的线程,猫和狗共享房屋中的一桶水,即房屋是线程的目标对象,房屋中的一桶水被猫和狗共享。猫和狗轮流喝水(狗喝的多,猫喝的少),当水被喝尽时,猫和狗进入死亡状态。猫或狗在轮流喝水的过程中,主动休息片刻(让Thread类调用sleep(int n)进入中断状态),而不是等到被强制中断喝水.
代码实现:(测试类有点看不懂)
多线程例题一
House类:
public class House implements Runnable { int waterAmount; //用int变量模拟水量 public void setWater(int w) { waterAmount = w; } public void run() { while(true) { String name=Thread.currentThread().getName(); if(name.equals("狗")) { System.out.println(name+"喝水") ; waterAmount=waterAmount-2; //狗喝的多 } else if(name.equals("猫")){ System.out.println(name+"喝水") ; waterAmount=waterAmount-1; //猫喝的少 } System.out.println(" 剩 "+waterAmount); try{ Thread.sleep(2000); //间隔时间 } catch(InterruptedException e){} if(waterAmount<=0) { return; } } } }
Test类:
public class Test{ public static void main(String args[ ]) { House house = new House(); house.setWater(10); Thread dog,cat; dog=new Thread(house); cat=new Thread(house); //cat和dog的目标对象相同 dog.setName("狗"); cat.setName("猫"); dog.start(); cat.start(); } }
多线程例题二
一个线程每隔1秒钟在命令行窗口输出本地机器的时间,在3秒钟后,该线程又被分配了实体,新实体又开始运行。因为垃圾实体仍然在工作,因此,在命令行每秒钟能看见两行同样的本地机器时间.
代码实现:
Clock类:
import java.util.Date; import java.text.SimpleDateFormat; public class Clock implements Runnable{ int time=0; SimpleDateFormat m=new SimpleDateFormat("hh:mm:ss"); Date date; public void run() { while(true) { date=new Date(); System.out.println(m.format(date)); time++; try { Thread.sleep(2000); }catch(InterruptedException e) { } if(time==3) { Thread thread=Thread.currentThread(); thread=new Thread(this); thread.start(); } } } }
Test类:
public class Test{ public static void main(String[] args) { Clock clock=new Clock(); Thread homeTime=new Thread(clock); homeTime.start(); } }
多线程例题三
有两个线程:student和teacher,其中student准备睡一小时后再开始上课,teacher在输出3句“上课”后,吵醒休眠的线程student。
代码实现:
ClassRoom类:
public class ClassRoom implements Runnable{ Thread student,teacher; ClassRoom(){ student=new Thread(this); teacher=new Thread(this); teacher.setName("王教授"); student.setName("小张"); } public void run() { if(Thread.currentThread()==student) { try {System.out.println(student.getName()+"正在睡觉"); Thread.sleep(1000*60*60); }catch(InterruptedException e) { System.out.println(student.getName()+"被老师吵醒了"); } System.out.println(student.getName()+"开始听课"); } else if(Thread.currentThread()==teacher) { for(int i=0;i<3;i++) { System.out.println("上课!"); try { Thread.sleep(500); }catch(InterruptedException e) { } } student.interrupt(); //吵醒学生 } } }
Test类:
public class Test{ public static void main(String[] args) { ClassRoom s=new ClassRoom(); s.student.start(); s.teacher.start(); } }