写两个线程,一个线程打印1-52,另一个线程打印A-Z,打印顺序为12A34B…5152Z
//写两个线程,一个线程打印1-52,另一个线程打印A-Z,打印顺序为12A34B...5152Z
class Print
{
private Integer num=1;
private Integer flag=1;
synchronized public void printNum()
{
while(num<27)
{
if(flag!=1)
{
try {
wait(); //等待打印字母
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//打印数字
if(num<27) //加判断是因为最后一次num=26,数字线程等待字母线程,当字母打印结束,
// num=27,会唤醒数字线程,那么数字线程将会以num=27继续执行
{
System.out.print(num*2-1);
System.out.print(num*2);
flag=2;
notify();//唤醒打印字母的线程
}
}
}
synchronized public void printLetter()
{
while(num<27)
{
if(flag!=2)
{
try {
wait(); //此时应该打印数字。等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//打印字母
System.out.print((char)(num-1+'A'));
num++;
flag=1;
notify(); //唤醒打印字母的线程
}
}
}
public class Print1A {
public static void main(String[] args)
{
Print print=new Print();
Thread numThread=new Thread(new Runnable() {
@Override
public void run() {
print.printNum();
}
});
Thread letterThread=new Thread(new Runnable() {
@Override
public void run() {
print.printLetter();
}
});
numThread.start();
letterThread.start();
}
}
12A34B56C78D910E1112F1314G1516H1718I1920J2122K2324L2526M2728N2930O3132P3334Q3536R3738S3940T4142U4344V4546W4748X4950Y5152Z
编写一个程序,启动三个线程,三个线程的名称分别是A,B,C;
// 每个线程将自己的名字在屏幕上打印5遍,打印顺序是
//ABCABCABCABCABC
//编写一个程序,启动三个线程,三个线程的名称分别是A,B,C;
// 每个线程将自己的名字在屏幕上打印5遍,打印顺序是
//ABCABCABCABCABC
class PrintABCI
{
private Integer flag=1;
private Integer count=1; //打印次数
public synchronized void printA()
{
while(flag!=1 )
{
try {
wait(); //等待打印B或C
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print('A');
flag=2;
notifyAll();
}
public synchronized void printB()
{
while(flag!=2 )
{
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print('B');
flag=3;
notifyAll();
}
public synchronized void printC()
{
while(flag!=3)
{
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print('C');
count++;
flag=1;
notifyAll();
}
}
public class PrintABC {
public static void main(String[] args) {
PrintABCI print=new PrintABCI();
new Thread(new Runnable()
{
@Override
public void run() {
for(int i=0;i<5;i++)
print.printA();
}
}).start();
new Thread((new Runnable() {
@Override
public void run() {
for(int i=0;i<5;i++)
print.printB();
}
})).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<5;i++)
print.printC();
}
}).start();
}
}