多线程:
例程1:使用Thread类实现线程
/**使用Thread类实现线程*/
public class ThreadTest extends Thread{ //指定类继承Thread类
private int count = 10;
public void run(){
while(true){
System.out.print(count+" "); //打印count变量
if(--count == 0){
System.out.println();
return;
}
}
}
public static void main(String[] args){
new ThreadTest().start();
}
}
程序运行结果:
10 9 8 7 6 5 4 3 2 1
例程2:
/**使用Runnable接口实现线程*/
/*
run()方法可以重写
*/
class RunnableDemo implements Runnable{ //定义一个类实现Runnable接口
private Thread t; //定义私有成员变量t
private String threadName; //定义字符串变量threadName
RunnableDemo(String name){
threadName = name;
System.out.println("Creating "+threadName);
}
public void run(){
System.out.println("Running "+threadName);
try{
for(int i = 4;i>0;i--){
System.out.println("Thread:"+threadName+","+i);
//让线程休眠一会儿
Thread.sleep(50);
}
}catch(InterruptedException e){
System.out.println("Thread "+threadName+" interrupted.");
}
System.out.println("Thread "+threadName+" exiting.");
}
public void start(){
System.out.println("Starting "+threadName);
if(t==null){
t=new Thread(this,threadName);
t.start();
}
}
}
public class RunnableTest{
public static void main(String args[]){
RunnableDemo R1 = new RunnableDemo("Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo("Thread-2");
R2.start();
}
}
程序运行结果:
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread:Thread-1,4
Running Thread-2
Thread:Thread-2,4
Thread:Thread-1,3
Thread:Thread-2,3
Thread:Thread-1,2
Thread:Thread-2,2
Thread:Thread-1,1
Thread:Thread-2,1
Thread Thread-1 exiting.
Thread Thread-2 exiting.