1.两个线程交替打印大小写字母“AaBbCc.....Zz”
public class RunTest {
public static void main(String[] args) {
Myprint mp = new Myprint();
new Capital(mp).start();
new Lowercase(mp).start();
}
}
class Myprint {
boolean flag = true;
int i = 0;
int j = 0;
public void Da() {
while (i < 26) {
if (flag) {
System.out.print((char) ('A' + i));
i++;
this.flag = false;
}
}
}
public void Xiao() {
while (j < 26) {
if (!flag) {
System.out.print((char) ('a' + j));
j++;
this.flag = true;
}
}
}
}
class Capital extends Thread {
Myprint my = null;
public Capital(Myprint my) {
this.my = my;
}
@Override
public void run() {
my.Da();//打印大写
}
}
class Lowercase extends Thread {
Myprint my = null;
public Lowercase(Myprint my) {
this.my = my;
}
@Override
public void run() {
my.Xiao();//打印小写
}
}
2.两个线程交替打印数字和字母“1A2B3C......26Z”
public class PrintLetter {
private static Object lock = new Object();
private static Thread th1 = new Thread() {
@Override
public void run() {
synchronized (lock) {
for (int i = 1; i <= 26; i++) {
System.out.println(i);
lock.notify();
try {
Thread.sleep(1000);
lock.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
};
private static Thread th2 = new Thread() {
@Override
public void run() {
synchronized (lock) {
for (int i = 1; i <= 26; i++) {
System.out.println((char) (i + 64));
lock.notify();
try {
Thread.sleep(1000);
lock.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
};
public static void main(String[] args) {
th1.start();
th2.start();
}
}
3.两个线程交替打印26个小写字母“abcd......z”
public class Print_letter implements Runnable{
char ch = 97;
@Override
public void run() {
while (true){
synchronized (this){
notify();
try {
Thread.currentThread().sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
if (ch < 123){
System.out.println(Thread.currentThread().getName() + " " + ch);
ch++;
try {
wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
Print_letter t = new Print_letter();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
t2.start();
}
}