可以继承Thread类也可以实现Runnable接口和Callable接口
继承Thread类
class Test extends Thread{
public void run() {
}
}
建议使用实现Runnable,方便多个线程操作同一个对象,比如下面这个,但是这样写存在并发问题。这里只是举例说明多个线程操作同一个对象。
实现Runnable接口
package hello;
import java.util.*;
public class Main implements Runnable{
private int ticket=10;
public static void main(String[] args) {
Main m=new Main();
new Thread(m,"江小鱼").start();
new Thread(m,"路演").start();
new Thread(m,"张冲").start();
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
if(ticket<=0) {
break;
}
System.out.println(Thread.currentThread().getName()+"拿到第"+ticket--+"张票");
}
}
}
实现Callable接口
package hello;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Main implements Callable<Boolean>{
private String url;
private String name;
private Download loader=new Download();
public Main(String url,String name) {
this.url=url;
this.name=name;
}
public Boolean call() throws Exception {
// TODO Auto-generated method stub
loader.download(url, name);
return true;
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
Main t1=new Main("1","1");
Main t2=new Main("2","2");
Main t3=new Main("3","3");
ExecutorService ser=Executors.newFixedThreadPool(3);
//Future用来保存多线程执行的结果
Future<Boolean> r1=ser.submit(t1);
Future<Boolean> r2=ser.submit(t2);
Future<Boolean> r3=ser.submit(t3);
boolean rs1=r1.get();
boolean rs2=r2.get();
boolean rs3=r3.get();
}
}
class Download{
public void download(String url,String name) {
System.out.println(url);
}
}