Java多线程
一、四种方法
1、继承Thread类
不建议使用,避免OOP单继承局限性
public class TestThread1 extends Thread {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("线程1" + i);
}
}
public static void main(String[] args) {
TestThread1 testThread1 = new TestThread1();
testThread1.start();
for (int i = 0; i < 200; i++) {
System.out.println("main" + i);
}
}
}
2、实现runnable接口
推荐使用,避免单继承局限性,方便一个对象被多个线程使用
public class TestThread3 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("线程1 y" + i);
}
}
public static void main(String[] args) {
TestThread3 testThread3 = new TestThread3();
// Thread thread = new Thread(testThread3);
// thread.start();
new Thread(testThread3).start();
for (int i = 0; i < 200; i++) {
System.out.println("main" + i);
}
}
}
3、Callable接口
实例必须实现Callable<>接口,重写Run方法
TestCallable t1 = new TestCallable();//创建服务
ExecutorService ser = Executors.newFixedThreadPool(1);//括号内为线程数
Future<Boolean> r1 = ser.submit(t1);
boolean rs1 = r1.get();
System.out.println(rs1);
ser.shutdownNow();
4、线程池
实例实现Runnable接口,重写Run方法
ExecutorService service = Executors.newFixedThreadPool(10);
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.shutdown();