java多线程简单Demo
TestThr.java;
class Mythread implements Runnable {
private Thread t;
private String threadName;
Mythread( String name) {
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 5; 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 TestThr{
public static void main(String args[]) {
Mythread t1 = new Mythread( "Thread-1");
t1.start();
Mythread t2 = new Mythread( "Thread-2");
t2.start();
}
}
构建和运行情况如下;
在java中可有两种方式实现多线程,一种是继承Thread类,一种是实现Runnable接口;
还没有评论,来说两句吧...