全站最帅😎
发布于 2020-04-17 / 1147 阅读
0
0

并发编程:线程基础和协作

线程常用的方法如图所示,下面我将通过实例一一讲解:
image.png

  1. start()方法,Thread的类中启动线程的方法,也是Java对线程的抽象:
    顺便说一下start()方法和run()方法的区别:

star()方法真正启动了一个线程,查看源码我们发现调用了start0()方法,这是一个native方法。
run()方法本质上我们就认为他是一个成员方法,调用run()方法直接是在main线程中运行的,并没有开辟一个新的线程。

public class StartAndRun {
    public static class ThreadRun extends Thread{

        @Override
        public void run() {
            int i = 90;
            while(i>0){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    //e.printStackTrace();
                }
                System.out.println("I am "+Thread.currentThread().getName()
                        +" and now the i="+i--);
            }
        }
    }

    public static void main(String[] args) {
        ThreadRun threadRun = new ThreadRun();
        threadRun.setName("threadRun"); // 注释此行可以注意观察threadName的输出
        threadRun.start();
    }
}
  1. sleep()方法:将当前线程挂起指定的时间,从操作系统层面来说就是当前线程在指定时间以内不再参与cpu的竞争。
  2. join()方法:调用join()方法的线程会使主线程进入等待池并等待,当调用线程执行完毕后主线程才会被唤醒。但是这并不影响同一时刻处在运行状态的其他线程。
public class MyUseJoin {

    static class Eat implements Runnable {
        private Thread thread;

        public Eat(Thread thread) {
            this.thread = thread;
        }

        @Override
        public void run() {
            int i = 0;
            while (i < 5 ) {
                i++;
                System.out.println(String.format("正在吃第%s口饭", i));
                try {
                    if(thread!=null) {
                        thread.join();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class HomeWork implements Runnable {
        @Override
        public void run() {
            int i = 0;
            while (i < 5 ) {
                i++;
                System.out.println(String.format("只有先做完%s作业才能干其他事情", i));
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("我也想吃饭");
        HomeWork homeWork = new HomeWork();
        Thread homeWorkThread = new Thread(homeWork);
        Eat eat = new Eat(homeWorkThread);
        Thread eatThread = new Thread(eat);
        eatThread.start();
        homeWorkThread.start();
        eatThread.join();
        System.out.println("我终于吃上饭了");
    }
}

打印结果

我也想吃饭
只有先做完1作业才能干其他事情
正在吃第1口饭
只有先做完2作业才能干其他事情
只有先做完3作业才能干其他事情
只有先做完4作业才能干其他事情
只有先做完5作业才能干其他事情
正在吃第2口饭
正在吃第3口饭
正在吃第4口饭
正在吃第5口饭
我终于吃上饭了

评论