//总结:重写的是run()方法,而不是start()方法,但是占用了继承的名额,Java中的类是单继承的
public class MyThread extends Thread{
public static void main(String[] args){
MyThread myThread = new MyThread();
//创建并启动线程
myThread.start();
}
@Override
public void run(){
//重写run方法
System.out.println("Hello");
}
}
//总结:实现Runnable接口,实现run()方法,使用依然要用到Thread类,这种方式更常用
//第一种写法
public class MyThread implements Runnable {
public static void main(String[] args){
Thread thread = new Thread(new MyThread());
//创建并启动线程
thread.start();
}
@Override
public void run(){
//重写run方法
System.out.println("Hello");
}
}
//第二种写法
public class MyThread{
public static void main(String[] args){
Thread thread = new Thread(new Runnable(){
public void run(){
//重写run方法
System.out.println("Hello");
}
});
//创建并启动线程
thread.start();
}
}
//第三种写法
public class MyThread implements Runnable {
public static void main(String[] args){
Thread thread = new Thread(()->System.out.println("Hello"));
thread.start();
}
}
//总结:与Runnable的区别在于,Callable可以获取返回结果
//实现Callable接口,实现call()方法,要使用Thread和FutureTask配合,这种方式支持拿到异步执行结果
public class MyThread implements Callable<String> {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<String> futureTask = new FutureTask<>(new MyThread());
Thread thread = new Thread(futureTask);
thread.start();
//此时是获取到的结果
String result = futureTask.get();
System.out.println(result);
}
@Override
public String call() throws Exception {
return "Hello";
}
}
//总结:实现Callable接口或者实现Runnable接口都可以,由ExecutorService创建线程
public class MyThread implements Runnable {
public static void main(String[] args){
// 创建10个数据级的线程池
ExecutorService threadPool = Executors.newFixedThreadPool(10);
threadPool.execute(new MyThread());
}
@Override
public void run(){
System.out.println("Hello");
}
}
评论