JAVA线程有两种创建方式:继承Thread类和实现Runnable接口
package test;
public class MyThread extends Thread {
private String name;
MyThread(String name) {
this.name = name;
}
//线程执行方法体
public void run() {
System.out.println(name + " is running.");
}
public static void main(String[] args) {
MyThread thread_1 = new MyThread("t1");
MyThread thread_2 = new MyThread("t2");
thread_1.start();//线程的执行采用start方法
thread_2.start();
//第二种方法
Runnable r1 = new MyThread("r1");
Runnable r2 = new MyThread("r2");
Thread th1 = new Thread(r1);
Thread th2 = new Thread(r2);
th1.start();
th2.start();
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test;
/**
*
* @author hhkun
*/
public class MyRunnable implements Runnable {
private String name;
MyRunnable(String name) {
this.name = name;
}
public void run() {
System.out.println(name + " is running.");
}
public static void main(String[] args) {
MyRunnable r1 = new MyRunnable("runnable1");
MyRunnable r2 = new MyRunnable("runnable2");
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}