关于java:两个线程交替打印A1B2C3-的几种实现方式

5次阅读

共计 1471 个字符,预计需要花费 4 分钟才能阅读完成。

有以下需要:
两个线程,须要打印字母和数字,格局 A1B2C3 …
这个问题波及到线程的期待,唤醒,线程间通信等常识。
上面看看实现代码:

办法 1 LockSupport

import java.util.concurrent.locks.LockSupport;

/**
 * @author liming
 * @date 2020/10
 * @description 交替打印 A1B2C3 ...
 */
public class AlternatePrint {

    static Thread t1 = null, t2 = null;

    public static void main(String[] args) {char[] aI = "1234567".toCharArray();
        char[] aC = "ABCDEFG".toCharArray();

        t1 = new Thread(new Runnable() {
            @Override
            public void run() {for (int i = 0; i < aC.length; i++) {
                    // 起始先打印一个字母
                    System.out.println(aC[i]);
                    // 打印完唤醒 t2 打印数字
                    LockSupport.unpark(t2);
                    // 本人阻塞,期待唤醒
                    LockSupport.park();}
            }
        });

        t2 = new Thread(new Runnable() {
            @Override
            public void run() {for (int i = 0; i < aI.length; i++) {
                    // 起始先阻塞期待
                    LockSupport.park();
                    // 被唤醒后打印数字
                    System.out.println(aI[i]);
                    // 唤醒 t1
                    LockSupport.unpark(t1);
                }
            }
        });

        t1.start();
        t2.start();}

}

办法 2 synchronized

import org.junit.Test;

/**
 * @author liming
 * @date 2020/10/14
 * @description 交替打印 A1B2C3 ...
 */

public class AlternatePrint {

    static Thread t1 = null, t2 = null;

    /**
     * 应用 synchronized
     */
    @Test
    public void alternatePrint() {Object lock = new Object();
        char[] aI = "1234567".toCharArray();
        char[] aC = "ABCDEFG".toCharArray();

        t1 = new Thread(new Runnable() {
            @Override
            public void run() {for (int i = 0; i < aC.length; i++) {synchronized (lock) {System.out.println(aC[i]);
                        lock.notify();
                        try {lock.wait();
                        } catch (InterruptedException e) {e.printStackTrace();
                        }
                    }
                }
            }
        });

        t2 = new Thread(new Runnable() {
            @Override
            public void run() {for (int i = 0; i < aI.length; i++) {synchronized (lock) {System.out.println(aI[i]);
                        lock.notify();
                        try {lock.wait();
                        } catch (InterruptedException e) {e.printStackTrace();
                        }
                    }
                }
            }
        });

        t1.start();
        t2.start();}

}

测试后果:

正文完
 0