多线程|多线程 奇数偶数按序输出 自学自用
package t3;
import java.util.ArrayList;
/*计算偶数*/
public class MyThread2 extends Thread {
private ArrayList
int count = 0;
public MyThread2(ArrayList
this.countList = countList;
}
@Override
public void run() {
while (true) {
synchronized (countList) {
while (count % 2 != 0) {
try {
count += 1;
countList.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
countList.add(count);
System.out.println("线程2(我打印的是偶数)-----" + countList.get(0));
countList.remove(0);
count += 1;
countList.notify();
}
}
}
}
========================================================
package t3;
import java.util.ArrayList;
/*计算奇数*/
public class MyThread1 extends Thread {
private ArrayList
int count = 0;
public MyThread1(ArrayList
this.countList = countList;
}
@Override
public void run() {
while (true) {
/*同步锁*/
synchronized (countList) {
while (count % 2 == 0) {
try {
count += 1;
countList.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
countList.add(count);
System.out.println("线程1(我打印的是奇数)-----" + countList.get(0));
countList.remove(0);
count+=1;
countList.notify();
}
}
}
}
================================================
package t3;
import java.util.ArrayList;
public class ThreadTest2 {
public static void main(String[] args) {
ArrayList
new MyThread1(countList).start();
new MyThread2(countList).start();
}
}
【多线程|多线程 奇数偶数按序输出 自学自用】package t3;
import java.util.ArrayList;
public class ThreadTest2 {
public static void main(String[] args) {
ArrayList
new MyThread1(countList).start();
new MyThread2(countList).start();
}
}
推荐阅读
- 放屁有这三个特征的,请注意啦!这说明你的身体毒素太多
- 爱就是希望你好好活着
- 昨夜小楼听风
- 知识
- 死结。
- 我从来不做坏事
- 烦恼和幸福
- 关于QueryWrapper|关于QueryWrapper,实现MybatisPlus多表关联查询方式
- Linux下面如何查看tomcat已经使用多少线程
- 说得清,说不清