编写两个线程,一个线程打印1-52的整数,另一个线程打印字母A-Z。打印顺序为12A34B56C….5152Z。

public class Test_52Z {
	public static void main(String[] args) {
		Printer2 p = new Printer2();
		//线程th1
		Thread th1 = new Thread() {
			public void run() {
				try {
					p.print52();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		//线程th1
		Thread th2 = new Thread() {
			public void run() {  //重写run
				try {
					p.printZ();
				} catch (Exception e) {
					e.printStackTrace();  //打印异常信息
				}
			}
		};
		//启动线程
		th1.start();
		th2.start();
	}
}
//Printer2类
class Printer2{
	private int flag = 0;
	//print52()方法
	public void print52() throws Exception {
		for (int i = 1; i <= 52; i = i+2) {
			synchronized (this) {  //synchronized关键字修饰非静态方法this,线性同步
				while (flag != 0) {
					this.wait();  //锁释放,进入等待
				}
				System.out.print(i);
				System.out.print(i + 1);
				flag = 1;  //修改标志,让th2执行
				this.notify();   //唤醒另一个线程
			}
		}
	}
	//printZ()方法
	public void printZ() throws Exception {
		for (char i = 'A' ; i <= 'Z'; i++) {
			synchronized (this) {
				while (flag != 1) {
					this.wait();  //锁释放,进入等待
				}
				System.out.print(i + " ");
				flag = 0;  //修改标志,让th1执行
				this.notify();   //唤醒另一个线程
			}
		}
	}
	
}

你可能感兴趣的:(java代码,java,开发语言)