java 线程间通信的几种方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27603235/article/details/78203074

1.如何让两个线程依次执行
假设有两个线程,一个线程A,一个线程B,两个线程分别依次打印 1-3 三个数字即可。

package Test;/**
/**
 * @author Administrator 
 * @createdate 2017-10-10
 */
public class demo1 {
    public static void main(String[] args){
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                printNumber("A");
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                printNumber("B");
            }
        });
        thread1.start();
        thread2.start();
    }
    private  static void printNumber(String threadname){
        int i=0;
        while (i++ <3){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(threadname + " print:" +i);
        }
    }
}

其中的 printNumber(String) 实现如下,用来依次打印 1, 2, 3 三个数字:通过将线程休眠的方式来控制两个线程一次来执行。
执行的结果如下:可以看到执行的结果是两个线程依次执行。这里写图片描述

2.如何让两个线程交叉顺序执行
我现在希望 A 在打印完 1 后,再让 B 打印 1, 2, 3,最后再回到 A 继续打印 2, 3。要如何来执行呢。看如下的代码

package Test;/**
/**
 * @author Administrator wangtao
 * @createdate 2017-10-10
 */
public class demo2 {
    public static void main(String[] args){
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                printNumber("A");
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("B 开始等待 A");
                try {
                    thread1.join();//我会等待线程1执行完成后再进行执行
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                printNumber("B");
            }
        });

        thread1.start();
        thread2.start();
    }

    private  static void printNumber(String threadname){
        int i=0;
        while (i++ <3){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(threadname + " print:" +i);
        }
    }
}

利用Thread.join()方法来实现,join()方法的作用是等待调用线程执行完之后再执行任务。看最后的执行结果知道,这里写图片描述
B线程是等到A全部执行完成之后才开始执行。

猜你喜欢

转载自blog.csdn.net/qq_27603235/article/details/78203074