package com.lxq.firstTest;
/**
* @作业5
* @功能:5、 编写程序实现两个线程一个线程输出1、2、3…26,另外一个线程实现a、b、c…Z,两个线程交替输出,如下:
* 1,a,2,b,3,c……
* @author: Qing
* @创建时间:2018/07/21
*/
public class Test05 {
public static void main(String[] args) {
TwoMethods tm= new TwoMethods();
TheInt ti = new TheInt(tm);
TheChar tc = new TheChar(tm);
new Thread(ti).start();
new Thread(tc).start();
}
}
//1-26数字的线程
class TheInt implements Runnable{
TwoMethods tm ;
public TheInt(TwoMethods tm) {
super();
this.tm = tm;
}
@Override
public void run() {
// TODO Auto-generated method stub
tm.showNum();
}
}
//a到z的字符线程
class TheChar implements Runnable{
TwoMethods tm ;
public TheChar(TwoMethods tm) {
super();
this.tm = tm;
}
@Override
public void run() {
// TODO Auto-generated method stub
tm.showChar();
}
}
//用于打印
class TwoMethods {
private int flag = 1;
//数字打印
public void showNum() {
// TODO Auto-generated method stub
for (int i = 1; i <=26; i++) {
synchronized (this) {
if (flag != 1) {
try {
this.wait();//等待
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.print(i + ",");
flag = 0;
this.notify();
}
}
}
//字符打印
public void showChar() {
// TODO Auto-generated method stub
for (int i = 0; i < 26; i++) {
synchronized (this) {
if (flag != 0) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.print((char) (i + 'a') + ",");
flag = 1;
this.notify();
}
}
}
}