两个线程顺序打印A1B2这个题目的解法

package com.jiahuilin;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

public class PrintTest1 {
    private static final Lock lock = new ReentrantLock();
    private static final Condition condition = lock.newCondition();

    static Thread t1, t2;

    public static void main(String[] args) {
        t1 = new Thread(() -> {

            String az = "ABCDEFGHIJKLMNPQRSTUVWXYZ";
                try{
                    lock.lock();
                    for (int i = 0; i < az.length(); i++) {
                        System.out.println(az.charAt(i));
                        condition.signal();
                        condition.await();
                    }
                    condition.signal();
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
        }, "t1");

        t2 = new Thread(() -> {
            int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25};
                try{
                    lock.lock();
                    for (int i = 0; i < arr.length; i++) {
                        System.out.println(arr[i]);
                        condition.signal();
                        condition.await();
                    }
                    condition.signal();
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }


//            try {
//                lock.lock();
//                for (int i = 0; i < arr.length; i++) {
//                    System.out.println(arr[i]);
//                   lock.notify();
//                    try {
//                        lock.wait();
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                }
//                lock.notify();
//            } catch (Exception e) {
//                e.printStackTrace();
//            } finally {
//                lock.unlock();
//            }
        }, "t2");
        t1.start();
        t2.start();

    }


}
package com.jiahuilin;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

public class PrintTest1 {
    private static final Lock lock =new ReentrantLock();

    static Thread t1, t2;
    public static void main(String[] args) {

        t1= new Thread(()->{

            String az = "ABCDEFGHIJKLMNPQRSTUVWXYZ";
            synchronized (lock){
                for(int i=0;i{
            int [] arr={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25};
            synchronized (lock){
                for(int i=0;i

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