设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。...

注:因为这4个线程共享J,所以线程类要写到内部类中。

public class TestThreads { private int j = 1; // 加线程 private class Inc implements Runnable { public void run() { inc(); } } // 减线程 private class Dec implements Runnable { public void run() { dec(); } } // 加1 private synchronized void inc() { j++; System.out.println(Thread.currentThread().getName() + "-inc:" + j); } // 减1 private synchronized void dec() { j--; System.out.println(Thread.currentThread().getName() + "-dec:" + j); } // 测试程序 public static void main(String[] args) { TestThreads test = new TestThreads(); // 创建两个线程类 Thread thread = null; Inc inc = test.new Inc(); Dec dec = test.new Dec(); // 启动4个线程 for (int i = 0; i < 2; i++) { thread = new Thread(inc); thread.start(); thread = new Thread(dec); thread.start(); } } }

加线程:每次对j加一。减线程:每次对j减一。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值