栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

线程的基本操作

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

线程的基本操作

1.线程的创建
## 方法一:继承Thread类
//创建线程方法一:继承Thread类,重写run()方法,调用start开启线程

// 线程开启不一定立即执行,由cpu调度执行
public class TestThread1 extends Thread{
    @Override
    public void run() {
//        run方法体
        for (int i = 0; i < 20; i++) {
            System.out.println("我在看代码"+i);
        }
    }

    public static void main(String[] args) {
//        main线程,主线程

//        创建一个线程对象
        TestThread1 testThread1 = new TestThread1();
//        调用start()方法开启线程   
        //用start开启线程:两个线程是同时进行的
//        如果调用run()方法,则是有先后顺序的
        testThread1.start();

        for (int i = 0; i < 20; i++) {
            System.out.println("我在学习多线程"+i);
        }
    }
}

方法二:实现runnable接口
//创建线程方式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) {
//      创建runnabl接口的实现类对象
        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);
        }
    }
}
案例:模拟龟兔赛跑
//模拟龟兔赛跑
public class Rece 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(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

//            判断比赛是否结束
            boolean flag = gameOver(i);
            if(flag){
                break;
            }
            System.out.println(Thread.currentThread().getName()+"-->跑了"+i+"步");
        }
    }

//    判断是否完成比赛
    private boolean gameOver(int steps){
        //判断是否有胜利者
        if(winner!=null) { //有胜利者了
            return true;
        } else {
            if(steps == 99){
                winner = Thread.currentThread().getName();
                System.out.println("winner is "+winner);
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Rece rece = new Rece();

        new Thread(rece,"兔子").start();
        new Thread(rece,"乌龟").start();
    }
}

2.静态代理
// 静态代理模式总结:
// 真实对象和代理对象都要实现同一个接口
//代理对象要代理真是对象

//好处: 代理对象可以做很多真是对象做不了的事情
// 真实对象专注做自己的事情

public class StaticProxy {
    public static void main(String[] args) {
        WeddingCompany weddingCompany = new WeddingCompany(new You());
        weddingCompany.HappyMarry();
    }
}

interface Marry{
    void HappyMarry();
}

//真是角色,你去结婚
class You implements Marry{

    @Override
    public void HappyMarry() {
        System.out.println("结婚了,超开心");
    }
}

//代理角色,帮助你结婚
class WeddingCompany implements Marry{
    private Marry target;

    public WeddingCompany(Marry target) {
        this.target = target;
    }

    @Override
    public void HappyMarry() {
        before();
        this.target.HappyMarry();
        after();
    }

    private void after() {
        System.out.println("结婚后收尾款");
    }

    private void before() {
        System.out.println("结婚前布置");
    }
}
3.线程同步
//不安全的买票
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTickt station = new BuyTickt();

        new Thread(station,"我").start();
        new Thread(station,"你").start();
        new Thread(station,"黄牛").start();
    }
}

class BuyTickt implements Runnable{
//    票
    private int ticketNums = 10;
    boolean flag = true;  //外部停止方式
    @Override
    public void run() {
//        买票
        while (flag) {
            buy();
        }
    }

//    synchronized 同步方法,锁的是this
    private synchronized void buy() {
//        判断是否有票
        if(ticketNums<=0){
            flag = false;
            return ;
        }
//        模拟延时
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        买票
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
    }
}

4.模拟死锁
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class DeadLock {
    public static void main(String[] args) {
        Makeup makeup = new Makeup(0,"我");
        Makeup makeup1 = new Makeup(1,"你");

        makeup.start();
        makeup.start();
    }
}

//口红
class Lipstick{

}

//镜子
class Mirror{

}

class Makeup extends Thread {

//    需要的资源只有一份,用static来保证只有一份
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    int choice; //选择
    String girlName; //使用化妆品的人

    public Makeup( int choice, String girlName) {
        this.choice = choice;
        this.girlName = girlName;
    }

    @Override
    public void run() {
//      化妆
        makeup();
    }

//    化妆,相互持有对方的锁,就是需要拿到对方的资源
    private void makeup(){
        if(choice==0){
            synchronized (lipstick){  //获得口红的锁
                System.out.println(this.girlName+"获得口红的锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (mirror){  //一秒钟后想获得镜子
                    System.out.println(this.girlName+"获得镜子的锁");
                }
            }
        } else {
            synchronized (mirror) {  //获得镜子的锁
                System.out.println(this.girlName + "获得镜子的锁");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (lipstick) {  //一秒钟后想获得口红
                    System.out.println(this.girlName + "获得口红的锁");
                }
            }
        }
    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/307112.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号