Java多线程 - 交替打印问题

第一个问题:两个线程交替打印  "1234567" 与 "ABCDEFG"  打印结果:"1A2B3C4D5E6F7G"

代码如下:

public class AlternatePrinting {

    static Thread t1 = null;
    static Thread t2 = null;

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

        t1 = new Thread(()->{
            for (char numerChar : charArray1){
                System.out.print(numerChar);
                LockSupport.unpark(t2);
                LockSupport.park();
            }
        });

        t2 = new Thread(()->{
            for (char numerChar : charArray2){
                LockSupport.park();
                LockSupport.unpark(t1);
                System.out.print(numerChar);
            }
        });

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

第二个问题:三个线程交替打印 ,A线程打印"A" ,B线程打印"B",C线程打印"C", 打印10遍

public class AlternatePrintingA {

    public static void main(String[] args) {

        final Lock lock = new ReentrantLock();
        Condition condition1 = lock.newCondition();
        Condition condition2 = lock.newCondition();
        Condition condition3 = lock.newCondition();

        Thread t1 = new Thread(() ->{
            lock.lock();
           try {
               for (int i = 0;i<10;i++){
                   System.out.print("A");
                   condition2.signal();
                   condition3.signal();
                   condition1.await();
               }
               condition2.signal();
               condition3.signal();
           }catch (Exception e){
           }finally {
               lock.unlock();
           }

        });

        Thread t2 = new Thread(() ->{
            lock.lock();
            try {
                for (int i = 0;i<10;i++){
                    System.out.print("B");
                    condition1.signal();
                    condition3.signal();
                    condition2.await();
                }
                condition1.signal();
                condition3.signal();
            }catch (Exception e){
            }finally {
                lock.unlock();
            }

        });

        Thread t3 = new Thread(() ->{
            lock.lock();
            try {
                for (int i = 0;i<10;i++){
                    System.out.print("C");
                    condition1.signal();
                    condition2.signal();
                    condition3.await();
                }
                condition1.signal();
                condition2.signal();
            }catch (Exception e){
            }finally {
                lock.unlock();
            }
        });

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

你可能感兴趣的:(多线程,java)