–原作者:尚硅谷-佟刚
package com.atweihai.thread;
/**
* 利用多线程:交替打印字母a-z
*
*/
public class PrintLetters implements Runnable{
char ch='a';
public synchronized void print (){
//防止打印字母z后面的字符
if(ch<='z'){
System.out.println(Thread.currentThread().getName() +": "+ ch);
ch++;
notify();
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void run() {
while(ch<='z'){
print();
}
}
public static void main(String[] args) {
PrintLetters printLetters=new PrintLetters();
Thread th1=new Thread(printLetters);
Thread th2=new Thread(printLetters);
th1.setName("线程-1");
th2.setName("线程-2");
th1.start();
th2.start();
}
}