多线程
package a___duoxiancheng; import javax.swing.plaf.synth.SynthSpinnerUI; //接力赛--跑一千米没人跑一百米,每十米显示信息 public class Relay implements Runnable{ private int num = 1000; public void run() { while(num>900) { synchronized (this) { if(num<100) { break; } if(Thread.currentThread().getName()==Thread.currentThread().getName()&&Thread.currentThread().getName()==Thread.currentThread().getName()) { break; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"拿到了接力棒"); for(int i = 0;i<100;i+=10) { System.out.println(Thread.currentThread().getName()+"跑了"+(i+10)+"米!"); } num -=100; } } } //接力赛测试类 public static void main(String[] args) { Relay r = new Relay(); for(int i =0;i<10;i++) { new Thread(r,(i+1)+"号选手").start(); } } }
package a___duoxiancheng; public class Piao implements Runnable{ private int num = 100; private int content = 0; public void run() { while(true) { synchronized (this) { if(num<1) { break; } num--; content++; try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"抢到了第"+content+"张票"+",剩余"+num+"张!"); if(Thread.currentThread().getName().equals("黄牛党")) { return; } } } } public static void main(String[] args) { Piao p = new Piao(); Thread t = new Thread(p,"老大"); Thread t1 = new Thread(p,"老二"); Thread t2 = new Thread(p,"黄牛党"); t.start(); t1.start(); t2.start(); } }
package a___duoxiancheng; //使用多线程模拟爬山 public class MyThread extends Thread { private String name; private int num; private int tiem; /** * @param name * @param num * @param tiem */ public MyThread(String name, int num, int tiem) { super(name); this.name = name; this.num = num*1000/100; this.tiem = tiem; } //实现接口中的抽象run方法 public void run() { String name = Thread.currentThread().getName(); while(true) { if(num<0) { break; } try { Thread.sleep(this.tiem); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(name+"爬完了100米"); num--; } System.out.println(name+"爬完了"); } public static void main(String[] args) { MyThread m1 = new MyThread("张三",1,500); MyThread m2 = new MyThread("李四",1,800); m1.start(); m2.start(); } }
package a___duoxiancheng; public class HoSpitalText { public static void main(String[] args) { Thread thread = new Thread(new Hospital()); thread.setPriority(Thread.MAX_PRIORITY); thread.start(); for(int i = 0;i<20;i++) { System.out.println("普通号:"+(i+1)+"正在看病"); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } if(i==9) { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }