1 用Runnable方式创建线程
/**
* 用Runnable方式创建线程
*/
public class RunnableStyle implements Runnable{
@Override
public void run() {
System.out.println("用Runnable方法实现线程");
}
public static void main(String[] args) {
Thread thread = new Thread(new RunnableStyle());
thread.start();
}
}
2 用Thread方式实现线程
/**
* 用Thread方式实现线程
*/
public class ThreadStyle extends Thread{
@Override
public void run() {
System.out.println("用Thread类实现线程");
}
public static void main(String[] args) {
new ThreadStyle().start();
}
}
思考:同时使用Runnable和Thread两种实现线程的方式
继承Thread会直接覆盖run方法,传递进去的Runnable是得不到执行的
/**
* 同时使用Runnable和Thread两种实现线程的方式
*/
public class BothRunnableThread {
public static void main(String[] args) {
new Thread(new Runnable() {
//重写覆盖了Runnable里面的run方法 这个run方法是得不到执行的
@Override
public void run() {
System.out.println("我来自Runnable");
}
}) {
@Override
public void run() {
System.out.println("我来自Thread");
}
}.start();
}
}