线程学习的几个实例
1.售票系统
public class DemoTest { public static void main(String args[]){ ThreadTest mtTest= new ThreadTest(); new Thread(mtTest).start(); new Thread(mtTest).start(); new Thread(mtTest).start(); } public boolean isNumber(String str){ char[] no=str.toCharArray(); for(int i=0;i<no.length;i++){ if(!(no[i]>='0' && no[i]<='9')){ return false; } } return true; } } class ThreadTest implements Runnable{ int tickets=100; @Override public void run() { // TODO Auto-generated method stub while(true){ saleTicket(); } } public synchronized void saleTicket(){ synchronized (this) { if(tickets>0){ try { Thread.sleep(100); System.out.println(Thread.currentThread().getName()+"----"+"ticket"+"--->"+tickets--); } catch (Exception e) { // TODO: handle exception } } } } }
2.存钱
public class ThreadTest_1 { public static void main(String args[]){ ThreadDemo mtDemo=new ThreadDemo(); new Thread(mtDemo,"小明").start(); //两个人去存款,一共存了6次,共600元 new Thread(mtDemo,"小红").start(); } } class ThreadDemo implements Runnable{ int account=0; @Override //每个人存3次钱,一次存100 public void run() { // TODO Auto-generated method stub for(int i=0;i<10;i++){ saveMoney(100); } } public synchronized void saveMoney(int money){ account = account+money; try { Thread.sleep(100); System.out.println(Thread.currentThread().getName()+"存入100元后,现在账户余额为"+account); } catch (InterruptedException e) { // TODO: handle exception } } }
3.火车过山洞
public class ThreadTest_2 { public static void main(String[] args) { // TODO Auto-generated method stub ThreadDemo_1 mtDemo=new ThreadDemo_1(); new Thread(mtDemo,"火车A").start(); new Thread(mtDemo,"火车B").start(); new Thread(mtDemo,"火车C").start(); new Thread(mtDemo,"火车D").start(); new Thread(mtDemo,"火车E").start(); } } class ThreadDemo_1 implements Runnable{ @Override public void run() { // TODO Auto-generated method stub throughHill(); } public synchronized void throughHill(){ try { Thread.sleep(1000); System.out.println("此时穿过山洞的火车是:"+Thread.currentThread().getName()); } catch (InterruptedException e) { // TODO: handle exception } } }