多线程02
package com.thread.demo01; //创建线程方式2:实现runnable接口,重写run方法,执行线程需要丢入runnable接口实现类,调用start public class TestThread3 implements Runnable{ @Override public void run() { //run方法线程体 for (int i = 0; i < 20; i++) { System.out.println("我在看代码----"+i); } } public static void main(String[] args) { //主线程main线程 //创建runnable接口的实现类对象 TestThread3 testThread3 = new TestThread3(); //创建线程对象,通过线程对象来开启我们的线程,代理 // Thread thread = new Thread(testThread3); // // thread.start(); //上面两句可以合并为下面这句: new Thread(testThread3).start(); for (int i = 0; i < 20; i++) { System.out.println("我在学习多线程---"+i); } } }
买火车票:
package com.thread.demo01; //多线程同时操作同一个对象 //买火车票的例子 //发现问题:多个线程操作同一个资源,线程不安全,数据紊乱 public class TestThread4 implements Runnable{ //票数 private int ticketnums=10; @Override public void run() { while (true){ if(ticketnums<=0){ break; } //模拟延时 try { Thread.sleep(200); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println(Thread.currentThread().getName()+"---->拿到了第"+ticketnums--+"票"); } } public static void main(String[] args) { TestThread4 testThread4 = new TestThread4(); new Thread(testThread4,"mao").start(); new Thread(testThread4,"mi").start(); new Thread(testThread4,"huanglao").start(); } }
龟兔赛跑:
package com.thread.demo01; //模拟龟兔赛跑 public class Race implements Runnable{ //胜利者 private static String winner; @Override public void run() { for (int i = 0; i <= 100; i++) { //模拟兔子休息 if(Thread.currentThread().getName().equals("兔子")&&i%10==0){ try { Thread.sleep(10); } catch (InterruptedException e) { throw new RuntimeException(e); } } //判断比赛是否结束 boolean flag=gameOver(i); //如果比赛结束就终止程序 if(flag){ break; } System.out.println(Thread.currentThread().getName()+"-->跑了"+i+"步"); } } //判断是否完成比赛 public boolean gameOver(int steps){ if(winner!=null){ return true; }{ if(steps>=100){ winner=Thread.currentThread().getName(); System.out.println("胜利者是:"+winner); return true; } } return false; } public static void main(String[] args) { Race race = new Race(); new Thread(race,"兔子").start(); new Thread(race,"乌龟").start(); } }