码迷,mamicode.com
首页 > 编程语言 > 详细

多线程编程

时间:2020-02-16 16:34:01      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:tor   image   模拟   name   read   ret   strong   胜利   pack   

一: 两种实现方式:

1.继承Thread类重写run方法
2.继承Runnable接口重写run方法(通常用这种,java单继承的局限性,后期还想继承其他类会无从下手)

二:简单demo1(多线程模拟买票)

package 多线程;

public class BuyTicket {
    public static void main(String[] args) {
        TickThread tt = new TickThread();
        Thread t1 = new Thread(tt,"张三");
        Thread t2 = new Thread(tt,"李四");
        Thread t3 = new Thread(tt,"王五");
        t1.start();
        t2.start();
        t3.start();
    }
}
class TickThread implements Runnable{
    private  int total = 10;
    @Override
    public void run() {
        while (total>=1) {
            total--;
            System.out.println(Thread.currentThread().getName() + "买了票,剩余" + total + "张");
        }
        System.out.println(Thread.currentThread().getName()+"发现售罄");
    }
}

技术图片
由于资源没有加锁,导致数据异常问题

三 简单demo2(模拟龟兔赛跑)

package 多线程;

public class RunGame {
    public static void main(String[] args) {
        Runner rn = new Runner();
        Thread rabbit = new Thread(rn,"rabbit");
        Thread tortoise = new Thread(rn,"tortoise");
        rabbit.start();
        tortoise.start();

    }
}
class Runner implements Runnable{
    private int stage = 100;
    private String winner=null;
    @Override
    public void run() {
       for(int i=1;i<=100;i++){
           if(isOver(i)==true) {
               Thread.currentThread().interrupt();
               break;
           }

       }

    }
    boolean isOver(int step){
        if (winner!=null){
            return true;
        }else{
            if(step==100){
                System.out.println(Thread.currentThread().getName()+"胜利!");
                winner=Thread.currentThread().getName();
                return true;
            }else{
                System.out.println(Thread.currentThread().getName()+"->"+step);
                return false;
            }
        }
    }
}

技术图片

多线程编程

标签:tor   image   模拟   name   read   ret   strong   胜利   pack   

原文地址:https://www.cnblogs.com/shuzi0806/p/12317137.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!