Java多线程之启动的模式:
1. 继承Thread类。
public class MyThread extends Thread{
public void run(){
for (int i = 0; i < 10; i++) {
System.out.println(i+"run...");
}
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
2.实现Runnable接口
实现接口,新建对象,传参进去。
public class MyThread implements Runnable{
public void run(){
for (int i = 0; i < 10; i++) {
System.out.println(i+"run...");
}
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread);
thread.start();
}
}
3.实现Callable接口,新建类对象,新建FutureTask类对象时传入当前类对象,接着新建Thread类对象时传入FutureTask类对象。
public class MyThread implements Callable {
public Object call() throws Exception {
for (int i = 0; i < 10; i++) {
System.out.println(i+"call");
}
return null;
}
public static void main(String[] args) {
Callable callable = new MyThread();
FutureTask futureTask = new FutureTask(callable);
Thread thread = new Thread(futureTask);
thread.start();
}
}
我们用一个卖票例子来解释 1和2的区别。
1.继承Thread类
package com.threadtest;
class MyThread extends Thread{
private int ticket = 10;
private String name;
public MyThread(String name){
this.name =name;
}
public void run(){
for(int i =0;i<500;i++){
if(this.ticket>0){
System.out.println(this.name+"卖票---->"+(this.ticket--));
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyThread mt1= new MyThread("一号窗口");
MyThread mt2= new MyThread("二号窗口");
MyThread mt3= new MyThread("三号窗口");
mt1.start();
mt2.start();
mt3.start();
}
}
2.实现Runnable接口
package com.threadtest;
class MyThread1 implements Runnable{
private int ticket =10;
private String name;
public void run(){
for(int i =0;i<500;i++){
if(this.ticket>0){
System.out.println(Thread.currentThread().getName()+"卖票---->"+(this.ticket--));
}
}
}
}
public class RunnableDemo {
public static void main(String[] args) {
MyThread1 mt = new MyThread1();
Thread t1 = new Thread(mt,"一号窗口");
Thread t2 = new Thread(mt,"二号窗口");
Thread t3 = new Thread(mt,"三号窗口");
t1.start();
t2.start();
t3.start();
}
}
运行结果,一个是
一号窗口卖票---->10
一号窗口卖票---->9
二号窗口卖票---->10
一号窗口卖票---->8
一号窗口卖票---->7
一号窗口卖票---->6
三号窗口卖票---->10
一号窗口卖票---->5
一号窗口卖票---->4
一号窗口卖票---->3
一号窗口卖票---->2
一号窗口卖票---->1
二号窗口卖票---->9
二号窗口卖票---->8
三号窗口卖票---->9
三号窗口卖票---->8
三号窗口卖票---->7
三号窗口卖票---->6
三号窗口卖票---->5
三号窗口卖票---->4
三号窗口卖票---->3
三号窗口卖票---->2
三号窗口卖票---->1
二号窗口卖票---->7
二号窗口卖票---->6
二号窗口卖票---->5
二号窗口卖票---->4
二号窗口卖票---->3
二号窗口卖票---->2
二号窗口卖票---->1
一号窗口卖票---->10
三号窗口卖票---->9
三号窗口卖票---->7
三号窗口卖票---->5
三号窗口卖票---->4
三号窗口卖票---->3
三号窗口卖票---->2
三号窗口卖票---->1
一号窗口卖票---->8
二号窗口卖票---->6
相当于 继承Thread类时,每个窗口都卖10张票,而实现Runnable接口时,三个窗口都在卖10张票
用接口的方式将代码和线程分离,更加清晰。
通过继承Thread类,每个线程都有一个相关联的对象。
使用Runnable接口,多线程可以共享同一个Runnable实例。