public class ThreadTest {
private int j;
public static void main(String args[]) {
ThreadTest tt = new ThreadTest();
Inc inc = tt.new Inc();
Dec dec = tt.new Dec();
Thread t = new Thread(inc);
t.start();
t = new Thread(dec);
t.start();
}
private synchronized void inc() {
System.out.println(Thread.currentThread().getName() + "-inc:" + ++j);
}
private synchronized void dec() {
System.out.println(Thread.currentThread().getName() + "-dec:" + --j);
}
class Inc implements Runnable {
public void run() {
inc();
}
}
class Dec implements Runnable {
public void run() {
dec();
}
}
}
设计2个线程,其中一个线程增加1,另外一个线程减少1。
最新推荐文章于 2023-07-27 21:46:24 发布
本文展示了一个使用Java实现的简单线程同步示例。该示例通过两个线程分别对同一个变量进行递增和递减操作来演示synchronized关键字的作用。通过观察输出结果可以了解到线程同步的基本原理。
5544

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



