[Java] 设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。 →→→→→进入此内容的聊天室

来自 , 2020-12-18, 写在 Java, 查看 121 次.
URL http://www.code666.cn/view/f57a2f55
  1. public class ThreadTest1{
  2. private int j;
  3. public static void main(String args[]){
  4. ThreadTest1 tt=new ThreadTest1();
  5. Inc inc=tt.new Inc();
  6. Dec dec=tt.new Dec();
  7. for(int i=0;i<2;i++){
  8. Thread t=new Thread(inc);
  9. t.start();
  10. t=new Thread(dec);
  11. t.start();
  12. }
  13. }
  14. private synchronized void inc(){
  15. j++;
  16. System.out.println(Thread.currentThread().getName()+"-inc:"+j);
  17. }
  18. private synchronized void dec(){
  19. j--;
  20. System.out.println(Thread.currentThread().getName()+"-dec:"+j);
  21. }
  22. class Inc implements Runnable{
  23. public void run(){
  24. for(int i=0;i<100;i++){
  25. inc();
  26. }
  27. }
  28. }
  29. class Dec implements Runnable{
  30. public void run(){
  31. for(int i=0;i<100;i++){
  32. dec();
  33. }
  34. }
  35. }
  36. }

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

这儿你可以回复上面这条便签

captcha