线程是JAVA的良好机制,也是很多程序必备的,只有有了良好的线程我们的程序才可以运行的良好,JAVA提供了thread这个类来创建线程,创建线程主要有两种方法,一重写方法,二,继承THREAD类。下面是继承自thread类的小例子。
public class YThread extends Thread{
static int k=0;
public YThread(String name)
{
super(name);
}
public void run()
{
k++;
System.out.println(getName()+"是第"+k+"个线程");
if(k==1){
this.yield();
}
System.out.println(getName() +"end");
}
public static void main (String args[])
{
YThread t1 = new YThread("thread1");
YThread t2 = new YThread("thread2");
YThread t3 = new YThread("thread3");
YThread t4 = new YThread("thread4");
YThread t5 = new YThread("thread5 我们不分先后啊");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
运行将随即产生不同的顺序,可能因为机器速度表现的不是很明显。
2,文件读取类filer
下面的小例子可以用来读取一个目录并且列出树状结构。
import java.io.*;
public class FileList{
public static void main(String[] args){
File f = new File("E:/mydao");
System.out.println(f.getName());
tree(f,1);
}
private static void tree(File f,int level){
String prestr="";
for(int i=0;i<level;i++){
prestr+=" ";
}
File[] childs = f.listFiles();
for(int i=0;i<childs.length;i++){
System.out.println(prestr+childs[i].getName());
if(childs[i].isDirectory()){
tree(childs[i] , level+1);
}
}
}
}