第一个方法是实现Runnable接口,如
- //实现Runnable接口开启线程
- public class Test2 {
-
- public static void main(String[] args) {
- MyRunnable m = new MyRunnable();
- Thread thread1 = new Thread (m);
- Thread thread2 = new Thread(m);
- thread1.start();
- thread2.start();
- System.out.println("main method");
- }
- }
- class MyRunnable implements Runnable{
- @Override
- public void run() {
- // TODO Auto-generated method stub
- System.out.println("a thread start");
- }
- }
复制代码 第二是从Thread继承,如
- /**
- *从Thread继承,并重写run方法
- * @author g
- *
- */
- public class Test3 extends Thread {
-
- public static void main(String[] args) {
- Test3 thread1 = new Test3();
- Test3 thread2 = new Test3();
- thread1.start();
- thread2.start();
- System.out.println("main method");
- }
-
- @Override
- public void run() {
- System.out.println("a thread start");
- }
- }
复制代码 |