继承Thread类
子类继承Thread类具备多线程能力
启动线程:子类对象.start()
不建议使用:避免OOP单继承局限性
public class testThread extends Thread{
@Override
public void run() {
// run方法线程体
for(int i = 0; i < 20; i++){
System.out.println("hello word"+i);
}
}
public static void main(String[] args) {
// 主线程
testThread testThread1 = new testThread();
testThread testThread2 = new testThread();
testThread testThread3 = new testThread();
// 调用start()方法开启线程
testThread1.start(); // start()方法会由cpu自由调用run()
testThread2.start(); // start()方法会由cpu自由调用run()
testThread3.start(); // start()方法会由cpu自由调用run()
}
}
实现Runnable接口
实现接口Runnable具有多线程能力
启动线程:传入目标对象+Thread对象.start()
推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
public class TestDemo implements Runnable{
// 票数
private int ticketNums = 10;
@Override
public void run() {
while (true){
if(ticketNums<=0){
break;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Thread.currentThread().getName 获得当前执行线程的名字
System.out.println(Thread.currentThread().getName()+"-->拿到了"+ ticketNums--+"票");
}
}
public static void main(String[] args){
TestDemo ticket = new TestDemo();
new Thread(ticket,"xiaoming").start();
new Thread(ticket,"teacher").start();
new Thread(ticket,"huangniu").start();
}
}
实现Callable接口
实现callable接口,返回返回值类型
重写call方法,需要抛出异常
创建目标对象
创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1);
提交执行:Future
获取结果:boolean r1 = result1.get();
public class callableTread implements Callable{ private String sentence1; // private String sentence2; // public callableTread(String sentence1, String sentence2){ this.sentence1 = sentence1; this.sentence2 = sentence2; } @Override public Boolean call() throws Exception { System.out.println(sentence1 + "," +sentence2); return true; } public static void main(String[] args) throws ExecutionException, InterruptedException { callableTread t1 = new callableTread("sad","very sad"); callableTread t2 = new callableTread("sad","so sad"); callableTread t3 = new callableTread("sad","pretty sad"); // 创建执行服务 ExecutorService ser = Executors.newFixedThreadPool(3); //提交线程执行 Future r1 = ser.submit(t1); Future r2 = ser.submit(t2); Future r3 = ser.submit(t3); // 获取结果 boolean rs1 = r1.get(); // get()会阻塞住线程? boolean rs2 = r2.get(); boolean rs3 = r3.get(); System.out.println(rs1); System.out.println(rs2); System.out.println(rs3); // 关闭服务 ser.shutdownNow(); }
关闭服务:ser.shutdownNow();



