两个线程线程交替打印的几种方式
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();
}
}
推荐阅读
- Linux下面如何查看tomcat已经使用多少线程
- 刘婵为何不娶关羽的女儿为妻子,而为何要娶张飞的两个女儿
- 多线程NSOperation
- 说睡
- 有人与我谈格局
- ||11|2019年9月9日
- 活的教导7:两个阶段
- 两个人在一起,最怕将就。
- spring|spring boot中设置异步请求默认使用的线程池
- 两个心得