展开全部
同时启动两个线程,让线程分别打印奇数和偶数。示例定义两个线程分别打印1000以内的奇偶数,同时为了看62616964757a686964616fe58685e5aeb931333332643331到并发效果,每个线程打印完一个数字后都会进行暂停:public static void main(String[] args) {
final int count = 1000;
new Thread(){
public void run() {
for(int i = 1; i <= count ;i=i+2) {
// 奇数,起始值为1,增长步长为2
try {
System.out.println("奇数线程:\t" + i);
// 暂停0.5秒
sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}.start();
new Thread(){
public void run() {
for(int i = 0; i <= count ;i=i+2) {
// 偶数,起始值为0,增长步长为2
try {
System.out.println("偶数线程:\t" + i);
// 暂停0.5秒
sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}.start();
}
输出结果:偶数线程:0
奇数线程:1
偶数线程:2
奇数线程:3
偶数线程:4
奇数线程:5
偶数线程:6
奇数线程:7
偶数线程:8
奇数线程:9
偶数线程:10
......
奇数线程:991
偶数线程:986
奇数线程:993
偶数线程:988
奇数线程:995
偶数线程:990
奇数线程:997
偶数线程:992
奇数线程:999
偶数线程:994
偶数线程:996
偶数线程:998
偶数线程:1000