package com.thread.test;
public class Thread1 {
private static int i = 0;
private static int statue = 0;
public static void main(String[] args) {
final Thread1 t = new Thread1();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (t) {
for(;i < 100;){
while(statue!=0){
try {
t.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
i++;
System.out.println(Thread.currentThread().getName()+":"+i);
statue = 1;
t.notifyAll();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (t) {
for(;i < 100;){
while(statue!=1){
try {
t.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
i++;
System.out.println(Thread.currentThread().getName()+":"+i);
statue = 0;
t.notifyAll();
}
}
}
}).start();
}
}
本文展示了一个使用Java实现的简单线程同步示例。通过两个线程交替修改共享变量并利用synchronized关键字及wait和notifyAll方法来控制线程的执行顺序,确保线程安全。
1083

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



