第一题:
package com.Thread;/** * 模拟爬山 * @author 陈明 * */public class ThreadDome extends Thread { private int shij; private int mishu; public ThreadDome( int shij, int mishu) { super(); this.shij = shij; this.mishu = mishu*100; } public void run() { for(int i=0;i<10;i++) { try { Thread.sleep(this.shij); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"爬了"+mishu*(i+1)+"米"); } System.out.println(Thread.currentThread().getName()+"到达终点"); }}
package com.Thread;public class ThreadDomeTest { public static void main(String[] args) { ThreadDome td = new ThreadDome(500,1); ThreadDome td2 = new ThreadDome(1500,1); Thread t1 = new Thread(td,"年轻人------"); Thread t2 = new Thread(td2,"老年人>>>>>"); t1.start(); t2.start(); }}
输出结果图:
第二题:
package com.Thread;/** * 创建线程 * @author 陈明 * */public class RunnableDome implements Runnable{ //子线程 public void run() { for(int i = 1;i<=20;i++) { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+":"+i+"在看病"); } }}
package com.Thread;public class RunnableTest { public static void main(String[] args) { RunnableDome t = new RunnableDome(); Thread t2 = new Thread(t,"VIP病人"); t2.start(); for(int i=1;i<=50;i++) { Thread.currentThread().setName("普通病人"); if(i==10) { try { t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+":"+i+"在看病"); } }}
输出结果图:
第三题:
package com.Thread;public class maipiao implements Runnable { public void run() { paobu(); } public synchronized void paobu() { System.out.println(Thread.currentThread().getName()+":接过接力棒"); for(int j=1;j<=10;j++) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+":"+"跑了"+j*10+"米"); } } public static void main(String[] args) { maipiao mp = new maipiao(); Thread t1 = new Thread(mp,"1号"); Thread t2 = new Thread(mp,"2号"); Thread t3 = new Thread(mp,"3号"); Thread t4 = new Thread(mp,"4号"); t1.start(); t2.start(); t3.start(); t4.start(); }}
输出结果图:
第四题:
package com.Thread;public class qiaoDome implements Runnable { private int piao = 20; //票数 private int jipiao = 0; //记录票数的 @Override public void run() { String s = Thread.currentThread().getName(); while(true) { synchronized (this) { if(piao<=0) { break; } piao--; jipiao++; System.out.println(s+"抢了第"+jipiao+"票"); } if(s.equals("黄牛党")) { break; } } }}
package com.Thread;public class qiaoTest { public static void main(String[] args) { qiaoDome qd = new qiaoDome(); Thread t1 = new Thread(qd,"逃跑跑"); Thread t2 = new Thread(qd,"张飘飘"); Thread t3 = new Thread(qd,"黄牛党"); t1.start(); t2.start(); t3.start(); }}
输出结果图:
第一次输出图:
第二次输出图: