java中的线程问题

首先给出一个思考题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class NameList
{
     private List names =  new ArrayList();
     public synchronized void add(String name)
     {
         names.add(name);
     }



     public synchronized void printAll()     {
         for ( int i =  0 ; i < names.size(); i++)
         {
             System.out.print(names.get(i) + ””);
         }
     }



 
     public static void main(String[]args)
     {
         final NameList sl =  new NameList();
         for ( int i =  0 ; i <  2 ; i++)
         {
             new Thread()
             {
                 public void run()
                 {
                     sl.add(“A”);
                     sl.add(“B”);
                     sl.add(“C”);
                     sl.printAll();
                 }
             } .start();
         }
     }
}

Which two statements are true if this class is compiled and run?

  • An exception may be thrown at runtime.
  • The code may run with no output, without exiting.
  • The code may run with no output, exiting normally(正常地).
  • The code may rum with output “A B A B C C “, then exit.
  • The code may rum with output “A B C A B C A B C “, then exit.
  • The code may ruin with output “A A A B C A B C C “, then exit.
  • The code may ruin with output “A B C A A B C A B C “, then exit.


分析:第一次println的字符个数肯定大于等于3,小于等于6;第二次println的字符个数肯定等于6;所以输出的字符中,后6位肯定是第二次输出的,前面剩下的就是第一次输出的。而且第一次的输出结果肯定是第二次输出结果的前缀
另外: 线程内是顺序执行的,线程间交叉进行

未完待续

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值