方式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();
//如果只是調(diào)用thread的run方法跑筝。則只是一個(gè)普通的方法調(diào)用堆生,不會(huì)有線程出來居砖。
}
}
方式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();
//如果只是調(diào)用thread的run方法。則只是一個(gè)普通的方法調(diào)用岳链,不會(huì)有線程出來。
}
}