1、实现Runnable接口,实现run方法
public class ThreadTest {
public static void main(String[] args) {
try {
// 调用方法本身\主线程运行
MyRunnable1 run1 = new MyRunnable1("test1");
run1.run();
// 新开线程
Thread t1 = new Thread(run1);
t1.setName("t1");
t1.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
class MyRunnable1 implements Runnable {
private String value;
public String getvalue() {
return value;
}
public void setvalue(String value) {
this.value = value;
}
public MyRunnable1(String value) {
this.value = value;
}
public void run() {
System.out.println("线程ID:" + Thread.currentThread().getId());
System.out.println("线程Name:" + Thread.currentThread().getName());
System.out.println("Runnable-Value:" + value);
System.out.println("-----------------------------------------------------------------");
}
}
2、直接继承Thread类,重写run方法
public class ThreadTest {
public static void main(String[] args) {
try {
// 主线程
System.out.println("线程ID:" + Thread.currentThread().getId());
System.out.println("线程Name:" + Thread.currentThread().getName());
// 新开线程
MyThread t3 = new MyThread("test3");
t3.setName("t3");
t3.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
class MyThread extends Thread {
private String value;
public String getvalue() {
return value;
}
public void setvalue(String value) {
this.value = value;
}
public MyThread(String value) {
this.value = value;
}
@Override
public void run() {
super.run();
System.out.println("线程ID:" + Thread.currentThread().getId());
System.out.println("线程Name:" + Thread.currentThread().getName());
System.out.println("MyThread-value:" + value);
System.out.println("-----------------------------------------------------------------");
}
}
3、采用匿名类方式,其实也是实现接口Runnable
public class ThreadTest {
public static void main(String[] args) {
try {
Thread t2 = new Thread(new Runnable() {
public void run() {
System.out.println("线程ID:" + Thread.currentThread().getId());
System.out.println("线程Name:" + Thread.currentThread().getName());
System.out.println("匿名类时间:" + java.util.Calendar.getInstance().getTimeInMillis());
System.out.println("-----------------------------------------------------------------");
}
});
t2.setName("t2");
t2.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}