java多线程打印问题

题目

创建两个线程,一个输出1-52,一个输出A-Z,输出格式:12A 34B 56C 78D…

解法

使用object超类的wait和notify方法。

/**
 * @author hht
 * @date 2020/10/15 15:00
 */
public class thread {
    
    

    public static void main(String[] args) {
    
    
        //创建一个对象,给两个线程共享
        Object lock=new Object();
        new Thread(new thread1(lock)).start();
        new Thread(new thread2(lock)).start();
    }
}
class thread1 implements Runnable{
    
    

    Object lock;
    public thread1(Object lock){
    
    
      this.lock=lock;
    }
    @Override
    public void run() {
    
    
        //同步锁,锁传递过来的lock对象,这个lock对象被两个线程共享
        synchronized (lock) {
    
    
            for (int i = 1; i <= 52; i++) {
    
    
                System.out.print(i);
                if (i % 2 == 0) {
    
    
                    try {
    
    
                        lock.notifyAll();
                        lock.wait();
                    } catch (InterruptedException e) {
    
    
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

class thread2 implements Runnable{
    
    

    Object lock;
    public thread2(Object lock){
    
    
        this.lock=lock;
    }
    @Override
    public void run() {
    
    
        synchronized (lock) {
    
    
            for (char i = 'A'; i <= 'Z'; i++) {
    
    
                System.out.print(i);
                try {
    
    
                    lock.notifyAll();
                    lock.wait();
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41120971/article/details/109098372