1. package com.kai.lesson1;
    2. //多个线程同时操作同一个对象
    3. //买火车票
    4. //问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱
    5. public class TestThread4 implements Runnable{
    6. //票数
    7. private int ticketNums=10;
    8. @Override
    9. public void run() {
    10. while (true){
    11. if(ticketNums<=0){
    12. break;
    13. }
    14. try {
    15. Thread.sleep(200);
    16. } catch (InterruptedException e) {
    17. e.printStackTrace();
    18. }
    19. System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"票");
    20. }
    21. }
    22. public static void main(String[] args) {
    23. TestThread4 ticket= new TestThread4();
    24. new Thread(ticket,"A").start();
    25. new Thread(ticket,"B").start();
    26. new Thread(ticket,"C").start();
    27. }
    28. }

    例子:
    龟兔赛跑

    1. package com.kai.lesson1;
    2. //模拟龟兔赛跑
    3. public class Race implements Runnable{
    4. private static String winner;
    5. @Override
    6. public void run() {
    7. for (int i=0;i<=100;i++){
    8. //模拟兔子休息
    9. if(Thread.currentThread().getName().equals("兔子") && i%10==0){
    10. try {
    11. Thread.sleep(0,2);
    12. } catch (InterruptedException e) {
    13. e.printStackTrace();
    14. }
    15. }
    16. //判断比赛是否结束
    17. Boolean flag=gameOver(i);
    18. if (flag){
    19. break;
    20. }
    21. System.out.println(Thread.currentThread().getName()+"-->跑了"+i+"步");
    22. }
    23. }
    24. //判断是否完成比赛
    25. private boolean gameOver(int steps){
    26. //判断是否有胜利者
    27. if (winner!=null){
    28. return true;
    29. }else{
    30. if(steps>=100){
    31. winner=Thread.currentThread().getName();
    32. System.out.println("winner is"+ winner);
    33. return true;
    34. }else {
    35. return false;
    36. }
    37. }
    38. }
    39. public static void main(String[] args) {
    40. Race race=new Race();
    41. new Thread(race,"乌龟").start();
    42. new Thread(race,"兔子").start();
    43. }
    44. }