方式1:
package threadimp;
import java.util.Random;
public class MyThread extends Thread{
@Override
public void run() {
String name = Thread.currentThread().getName();
Random r = new Random();
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(r.nextInt(10) * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name + "------" + i);
}
}
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start();
thread2.start();
//如果只是调用thread的run方法。则只是一个普通的方法调用,不会有线程出来。
}
}
方式2:
package threadimp;
import java.util.Random;
public class MyRunnableThread implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
String name = Thread.currentThread().getName();
Random r = new Random();
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(r.nextInt(10) * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name + "--runnable----" + i);
}
}
public static void main(String[] args) {
Thread thread1 = new Thread(new MyRunnableThread());
Thread thread2 = new Thread(new MyRunnableThread());
thread1.start();
thread2.start();
//如果只是调用thread的run方法。则只是一个普通的方法调用,不会有线程出来。
}
}