设计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. }    
评论
chenchuxin 2008-03-09
t=new Thread(dec); //前面不要加Thread吗
chenchuxin 2008-03-09
public class ThreadTest1 {
private int j;
public static void main(String args[]){
ThreadTest1 tt=new ThreadTest1();
Inc inc=tt.new Inc();
Dec dec=tt.new Dec();

for(int i=0;i<2;i++){
Thread t=new Thread(inc);
t.start();
t=new Thread(dec);
t.start();
}
}

private synchronized void inc(){
j++;
System.out.println(Thread.currentThread().getName()+"-inc:"+j);
}

private synchronized void dec(){
j--;
System.out.println(Thread.currentThread().getName()+"-dec"+j);
}

class Inc implements Runnable{

public void run(){
for(int i=0;i<100;i++){
inc();
}
}
}

class Dec implements Runnable{
public void run(){
for(int i=0;i<100;i++){
dec();
}
}
}
}






//??? 为什么可以写成tt.new 这样子的呢,看不懂,涉及哪方面的知识呢;
这是实例化一个内部类对象。
//???为什么要加锁呢 不加可以吗
加锁保护数据在被一个线程访问期间不能被其它线程序访问!你上厕所的时候当然要把门锁好,要不妇女闯进来不坏事了?你完事后再打开门,让别人来用,一样的道理!呵呵~~~
//???currentThread()有什么作用呢是什么方法 //???getname呢
currentThread方法获得当前在运行的线程,getname获得当前线程的名字!(多看API文档)
chenchuxin 2007-12-09
CSDN上发帖 怄死我了;
发表评论

您还没有登录,请登录后发表评论

chenchuxin
搜索本博客
存档
最新评论