5、线程--线程通信

使用线程进行打印a-z

开启两个线程进行交替打印

测试代码如下:

public class printTest implements Runnable{

    private char c = 'a';
    
    public synchronized void print(){
        if(c <= 'z'){
            System.out.println(Thread.currentThread().getName() + "---" + c);
            c++;
            //唤醒
            notify();
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
    }
    public void run() {
        while(c <= 'z'){
            print();
        }
    }
}
public static void main(String[] args) {
        printTest r = new printTest();
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        
        t1.start();
        t2.start();
        
    }

思想:

在启动线程之后

线程1启动之后首先进行相关的操作,在进行唤醒其他线程,然后再让自己进行等待

线程2启动之后(可能处于等待状态,等待其他的线程将其唤醒)

在得到资源分配之后,首先进行相关的操作,在进行唤醒其他线程(此时唤醒的是线程1),然后再让自己进入等待状态

以此循环进行所以此时可以隔离打印a-z

原文地址:https://www.cnblogs.com/Mrchengs/p/10807015.html