第一种:
继承Thread类实现多线程
直接继承Thread类,并且覆写其中的run()方法(相当于主类中的main()方法)
此处每一个线程对象只能启动一次否则会抛出异常(RunTimeException)。
继承Thread类实现多线程会有单继承局限。
class MyThread extends Thread{
private String title;
public MyThread(String title) {
super();
this.title = title;
}
public void run () {
for(int i=0;i<10;i++) {
System.out.println(this.title+" "+Thread.currentThread().getName()+"、i :"+i);
}
}
}
public class Test2 {
public static void main(String[] args) {
MyThread myThread=new MyThread("微风");
Thread thread=new Thread(myThread,"线程1");
Thread thread2=new Thread(myThread,"线程2");
thread.start();
thread2.start();
}
}
第二种:
Runnable接口实现多线程。
此时MyThread类实现了Runnable接口,但是继承的不再是Thread类,虽然解决了Thread的单继承局限问题,但是没有start()方法被继承,此时需注意,Thread类中提供了一个构造方法,public Thread(Runnable target),可以接受Runnable的接口对象,
class MyThread implements Runnable{
private String title;
public MyThread(String title) {
super();
this.title = title;
}
public void run () {
for(int i=0;i<10;i++) {
System.out.println(this.title+" "+Thread.currentThread().getName()+"、i :"+i);
}
}
}
public class Test2 {
public static void main(String[] args) {
MyThread myThread=new MyThread("微风");
Thread thread=new Thread(myThread,"线程1");
Thread thread2=new Thread(myThread,"线程2");
thread.start();
thread2.start();
使用匿名内部类进行Runnable创建
public class Test2 {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("HelloWorld");
}
}).start();
}
}
使用lamda表达式进行Runnable对象创建
public class Test2 {
public static void main(String[] args) {
Runnable runnable=() -> System.out.println("helloworld");
Thread thread=new Thread(runnable);
thread.start();
}
}
继承 Thread与实现Runnable区别
a.实现Runnable可以避免单继承局限
b.使用Runnable接口来实现多线程而已更好的体现出程序共享的概念
第三种:Callable实现多线程
不管何种情况,想要启动多线程只有Thread类中Start()方法
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
class MyThread implements Callable<String>{
private int ticket=10;
public String call() {
while(ticket>0) {
System.out.println("剩余票数"+this.ticket--);
}
return "票卖完了";
}
}
public class Test2 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
FutureTask<String> task=new FutureTask<>(new MyThread());
new Thread(task,"黄牛A").start();
new Thread(task,"黄牛B").start();
System.out.println(task.get());
}
}
线程五种状态间的相互转换