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

设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。
java面试题。在网上搜到了代码,放入记事本清出一下格式,就可以在eclipse中运行了;
java 代码
  1.   
  2. public class ThreadTest1{   
  3. private int j;   
  4. public static void main(String args[]){   
  5. ThreadTest1 tt=new ThreadTest1();   
  6. Inc inc=tt.new Inc();   
  7. Dec dec=tt.new Dec();   
  8. for(int i=0;i<2;i++){   
  9. Thread t=new Thread(inc);   
  10. t.start();   
  11. t=new Thread(dec);   
  12. t.start();   
  13. }   
  14. }   
  15. private synchronized void inc(){   
  16. j++;   
  17. System.out.println(Thread.currentThread().getName()+"-inc:"+j);   
  18. }   
  19. private synchronized void dec(){   
  20. j--;   
  21. System.out.println(Thread.currentThread().getName()+"-dec:"+j);   
  22. }   
  23. class Inc implements Runnable{   
  24. public void run(){   
  25. for(int i=0;i<100;i++){   
  26. inc();   
  27. }   
  28. }   
  29. }   
  30. class Dec implements Runnable{   
  31. public void run(){   
  32. for(int i=0;i<100;i++){   
  33. dec();   
  34. }   
  35. }   
  36. }   
  37. }    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值