22.说出一些常用的类,包,接口,请各举5个? 答案:常用类-System,ArrayList,FileInputStream,Thread,Socket.
常用的包-java.io,java.util,java.sql,java.javax.naming,java.net 常用接口-Collection,Connection, Cloneable, Comparable, Serializable
23.说出ArrayList,Vector, LinkedList的存储性能和特性. 答案:ArrayList和Vector都是使用数组方式存储数据,此数组元素数大于实际存储的数据以便增加和插入元素,它们都允许直接按序号索引元素,但是插入元素要涉及数组元素移动等内存操作,所以索引数据快而插入数据慢,Vector由于使用了synchronized方法(线程安全),通常性能上较ArrayList差,而LinkedList使用双向链表实现存储,按序号索引数据需要进行前向或后向遍历,但是插入数据时只需要记录本项的前后项即可,所以插入速度较快。
24.设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。
注:因为这4个线程共享J,所以线程类要写到内部类中。
加线程:每次对j加一。
减线程:每次对j减一。 public class TestThreads
{
private int j=1;
//加线程
private class Inc implements Runnable
{
public void run()
{
for(int i = 0;i < 10;i++)
{
inc();
}
}
}
//减线程
private class Dec implements Runnable
{
public void run()
{
for(int i = 0;i < 10;i++)
{
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();
}
}
}