1.继承Thread类,重写该类的run()方法。
package samTest; import java.util.Scanner; /** * Created by Sam on 2018-01-02. */ public class ThreadTest { public static void main(String[] args) { Scanner in = new Scanner(System.in); for (int i = 0; i < 3; i++) { int flag = in.nextInt(); Thread t = new MyThread(flag); t.start(); System.out.println(Thread.currentThread().getName() + " " + i); } } } class MyThread extends Thread { private Integer threadFlag; public MyThread(Integer threadFlag) { this.threadFlag = threadFlag; } @Override public void run() { System.out.println(threadFlag); } }
2.实现Runnable接口,并重写该接口的run()方法,该run()方法同样是线程执行体,创建Runnable实现类的实例,并以此实例作为Thread类的target来创建Thread对象,该Thread对象才是真正的线程对象。
package samTest; import java.util.Scanner; /** * Created by Sam on 2018-01-02. */ public class ThreadTest { public static void main(String[] args) { Scanner in = new Scanner(System.in); for (int i = 0; i < 3; i++) { int flag = in.nextInt(); Runnable r = new MyRunnable(flag); Thread t = new Thread(r); t.start(); System.out.println(Thread.currentThread().getName() + " " + i); } } } class MyRunnable implements Runnable { private Integer threadFlag; public MyRunnable(Integer threadFlag) { this.threadFlag = threadFlag; } public void run() { System.out.println(threadFlag); } }