创建线程的多种方式
继承Thread类
class A extends Thread {
@Override
public void run() {
System.out.println("A");
}
}
public static void main(String[] args) {
new A().start();
}
实现Runnable接口
class B implements Runnable {
@Override
public void run() {
System.out.println("B");
}
}
public static void main(String[] args) {
Thread t = new Thread(new B());
t.start();
}
匿名内部类
/* 方式一 */
new Thread() {
public void run() {
System.out.println("A");
}
}.start();
/* 方式二 */
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("B");
}
}).start();
/* 两者都写输出D,因为重写了父类中的run方法 */
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("C");
}
}) {
public void run() {
System.out.println("D");
}
}.start();
Callable(返回结果、抛出异常)
class D implements Callable<Integer> {
@Override
public Integer call() throws Exception {
Thread.sleep(2000);
System.out.println("D");
return 1;
}
}
public static void main(String[] args) {
FutureTask<Integer> task = new FutureTask<>(new D());
new Thread(task).start();
try {
/* 如果任务没完成则会阻塞直到任务完成 */
int res = task.get();
System.out.println("结果为:" + res); //结果为:1
} catch (Exception e) {
System.err.println("出现异常");
}
}
定时器
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("here");
}
}, 1000, 5000); //每隔5秒执行一次,1秒后执行
线程池
ExecutorService es = Executors.newFixedThreadPool(2);
for (int i = 0; i <20; i++) {
es.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
}
es.shutdown();
输出:
pool-1-thread-1
pool-1-thread-2
pool-1-thread-2
pool-1-thread-1
...
Lambda表达式实现
????????????
网友评论