继承Thread类
有单继承局限
public class Test extends Object {public static void main(String[] args) throws Exception {Book book1=new Book("书1",99);Book book2=new Book("书2",1231);book1.start();book2.start();}}//线程操作类class Book extends Thread{private String title;private Integer price;public Book() {}public Book(String title, Integer price) {this.title = title;this.price = price;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public Integer getPrice() {return price;}public void setPrice(Integer price) {this.price = price;}@Overridepublic void run() {System.out.printf("书名 : %s , 价格 : %d \n",this.title,this.price);}}
实现Runnable接口
有效避免单继承局限问题,多线程首选
public class Test extends Object {public static void main(String[] args) throws Exception {Book book1=new Book("书1",99);Book book2=new Book("书2",1231);new Thread(book2).start();new Thread(book1).start();}}class Book implements Runnable{private String title;private Integer price;public Book() {}public Book(String title, Integer price) {this.title = title;this.price = price;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public Integer getPrice() {return price;}public void setPrice(Integer price) {this.price = price;}@Overridepublic void run() {System.out.printf("书名 : %s , 价格 : %d \n",this.title,this.price);}}
使用Callable接口实现多线程
JDK1.5开始提供Callable接口 java.util.concurrent.Callable
call方法可以实现线程操作数据的返回,返回数据类型由泛型决定
public interface Callable<V> {/*** Computes a result, or throws an exception if unable to do so.** @return computed result* @throws Exception if unable to compute a result*/V call() throws Exception;}
FutureTask
FutureTask
1.FutureTask.pdf
注意.Callable只是胜在又返回值.Runnable还是使用最广泛的
public class Test extends Object {public static void main(String[] args) throws Exception {FutureTask<String> futureTask=new FutureTask<>(new Book("书1",455));new Thread(futureTask).start();for (int i = 0; i < 1000; i++) {System.out.println("测试语句"+i);}System.out.println(futureTask.get());for (int i = 0; i < 1000; i++) {System.out.println("阿巴阿巴"+i);}}}//线程操作类class Book implements Callable<String>{private String title;private Integer price;public Book() {}public Book(String title, Integer price) {this.title = title;this.price = price;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public Integer getPrice() {return price;}public void setPrice(Integer price) {this.price = price;}@Overridepublic String call() throws Exception {for (int i = 0; i < 1000; i++) {System.out.println("子线程"+i);}System.out.printf("书名 : %s , 价格 : %d \n",this.title,this.price);return "输出完成";}}
