/** traversing elements */
import java.util.*;
class Traversor extends Thread
{
Enumeration e;
public Traversor(Enumeration e)
{
this.e=e;
}
public void run()
{
System.out.println("new thread started, traversing vector elements.....");
while(e.hasMoreElements())
{
System.out.println(e.nextElement());
try
{
Thread.sleep(4000);
}
catch(Exception ex)
{}
}
System.out.println("new thread completed");
}
}
class vectortest{
public static void main(String args[])
{
System.out.println("main thread started, creating vector...");
Vector v=new Vector();
v.addElement("one");
v.add("three");
v.add(1,"two");
Enumeration e=v.elements();
System.out.println("vector created ,enumeration obtained");
Traversor th=new Traversor(e);
th.start();
System.out.println(" new thread launched , suspending main thread");
try{
Thread.sleep(1000);
}
catch(Exception ex)
{}
System.out.println("main thread resumed,modifying vector");
v.add("four");
v.add("five");
System.out.println("vector modified, main thread completed");
}
}
答案 0 :(得分:0)
Java引入(相当晚)将Vector
Object
的{{1}}集合项列为Vector<T>
,其中T
是给定的类型参数,如{{1} }。 (它被称为泛型类型。)
现在编译器可以&#34;检查&#34;项目类型是否正常。
Vector<String>
顺便说一句,Vector和Enumeration相当古老。实际上现在很少见到Vector。
class Traversor<T> extends Thread {
Enumeration<T> e;
public Traversor(Enumeration<T> e) {
this.e = e;
}
public void run() {
System.out.println("new thread started, traversing vector elements.....");
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
try {
Thread.sleep(4000);
} catch (Exception ex) {
}
}
System.out.println("new thread completed");
}
}
class VectorTest {
public static void main(String args[]) {
System.out.println("main thread started, creating vector...");
Vector<String> v = new Vector<>();
v.addElement("one");
v.add("three");
v.add(1, "two");
Enumeration<String> e = v.elements();
System.out.println("vector created ,enumeration obtained");
Traversor<String> th = new Traversor<>(e);
th.start();
System.out.println(" new thread launched , suspending main thread");
try {
Thread.sleep(1000);
} catch (Exception ex) {
}
System.out.println("main thread resumed,modifying vector");
v.add("four");
v.add("five");
System.out.println("vector modified, main thread completed");
}
}