public class test {
//定义打印的方法
public synchronized void print(String str){
notify();
System.out.println(str);
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//定义打印奇数的线程类
class odd implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=1;i<100;i+=2){
print("o"+i);
}
}
}
//定义打印偶数的线程类
class even implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=2;i<=100;i+=2){
print("e"+i);
}
}
}
public static void main(String[] args) {
test p = new test();
odd o = p.new odd();
even e = p.new even();
new Thread(o).start();
new Thread(e).start();
}
}
结果:


本文展示了一个使用Java实现的线程同步示例,通过synchronized关键字和wait/notify机制,实现了两个线程分别打印奇数和偶数,确保了线程间的正确交互。
625

被折叠的 条评论
为什么被折叠?



