public class 交替输出 {
【两个线程交替输出1-26和A-Z】public static void main(String[] args) throws InterruptedException {
Num num = new Num(1,'A');
Thread t1 = new Thread(new Odd(num));
t1.setName("t1");
Thread t2 = new Thread(new Even(num));
t2.setName("t2");
t1.start();
Thread.sleep(1000);
t2.start();
}
}
//共享数据
class Num{
int count;
//输出数字
char c;
//输出字符
public Num(int count,char c) {
super();
this.count = count;
this.c = c;
}
//打印奇数
public synchronized void printOdd() throws InterruptedException {
System.out.println(Thread.currentThread().getName() +"-->" +(count++));
this.notifyAll();
this.wait();
//t1线程无期限的等待
Thread.sleep(1000);
}
//打印偶数
public synchronized void printEven() throws InterruptedException {
System.out.println(Thread.currentThread().getName() +"-->" +(c++));
this.notifyAll();
this.wait();
//t2线程无期限的等待
Thread.sleep(1000);
}
}
//线程1
class Odd implements Runnable{
Num num;
public Odd(Num num) {
super();
this.num = num;
}
public void run() {
while (true) {
//打印奇数
try {
num.printOdd();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//线程2
class Even implements Runnable{
Num num;
public Even(Num num) {
super();
this.num = num;
}
public void run() {
while (true) {
//打印偶数
try {
num.printEven();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
推荐阅读
- Java|Java基础——数组
- 人工智能|干货!人体姿态估计与运动预测
- java简介|Java是什么(Java能用来干什么?)
- Java|规范的打印日志
- Linux|109 个实用 shell 脚本
- 程序员|【高级Java架构师系统学习】毕业一年萌新的Java大厂面经,最新整理
- Spring注解驱动第十讲--@Autowired使用
- SqlServer|sql server的UPDLOCK、HOLDLOCK试验
- jvm|【JVM】JVM08(java内存模型解析[JMM])
- 技术|为参加2021年蓝桥杯Java软件开发大学B组细心整理常见基础知识、搜索和常用算法解析例题(持续更新...)