1. 创建两个线程,其中一个输出1-52,另外一个输出A-Z。输出格式要求:12A 34B 56C 78D
// 同步方法 synchronized修饰函数
// 思考:如何保证主线程最后的结束而非阻塞?
//注意: notifyall()的位置在当前线程wait()的前面
//java print不换行 println自动换行
// 思考:如何保证主线程最后的结束而非阻塞?
//注意: notifyall()的位置在当前线程wait()的前面
public class examination_16_1 {
// 这个类相当于共享变量
//同步监视器类,提供线程安全的方法
class printResult{
private int number=1;
private char character='A';
//提供两个synchronized方法
// synchronized方法 ;notifyall()的位置在当前线程wait()的前面
public synchronized void printnumber(){
System.out.print(number+""+(number+1));
number+=2;
notifyAll();
try {
// 大于52之后不再等待;
if (number <= 52) wait();
//使用while(number <= 52) wait();会一直循环,后面notify也跳不出来
} catch (Exception e) {
System.out.println(e.toString());
}
}
public synchronized void printcharacter(){
System.out.println(character+" ");
character+=1;
notifyAll();
try {
// 大于Z之后不再等待;如果不加最后不会结束!!阻塞了
if(character<='Z') wait();
}catch (Exception e){
System.out.println(e.toString());
}
}
}
class Number implements Runnable{
private printResult printresult;
public Number(printResult p){
this.printresult=p;
}
private int i=0;
public void run(){
for(;i<26;i++) {
//调用同步监视器中的方法
printresult.printnumber();
//System.out.println(Thread.currentThread().getName()+" "+i);
}
}
}