Java线程
创建线程的方法
- 继承 Thread 类
- 实现 Runnable 接口
- 实现 Callable 接口
- 使用ThreadPool创建
线程常用的方法
public void run()
public void start()
thread.join()
等待该线程死亡Thread.currentThread().getName()
获取当前线程的名称Thread.currentThread().setName("主线程");
设置当前线程的名称
线程的实现
继承 Thread 类
public class MyTest01 {
public static void main(String[] args) {
Thread.currentThread().setName("主线程");
System.out.println(Thread.currentThread().getName()+":"+"我是主线程");
ThreadDemo1 thread1 = new ThreadDemo1();
thread1.setName("线程一");
thread1.start();
}
}
class ThreadDemo1 extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+":"+"我是线程一");
}
}
实现 Runnable 接口
public class MyTest02 {
public static void main(String[] args) {
Thread.currentThread().setName("主线程");
System.out.println(Thread.currentThread().getName()+":"+"我是主线程");
Thread thread2 = new Thread(new ThreadDemo2());
thread2.setName("线程二");
thread2.start();
}
}
class ThreadDemo2 implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":" + "我是线程二");
}
}
实现 Callable 接口
public class MyTest03 {
public static void main(String[] args) throws Exception{
Thread.currentThread().setName("主线程");
System.out.println(Thread.currentThread().getName()+":"+"我是主线程");
FutureTask<String> task = new FutureTask<String>(new ThreadDemo3());
Thread thread3 = new Thread(task);
thread3.setName("线程三");
thread3.start();
String result = task.get();
System.out.println(result);
}
}
class ThreadDemo3 implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println(Thread.currentThread().getName()+":"+"我是线程三");
return Thread.currentThread().getName()+":"+"结束返回值";
}
}
使用ThreadPool创建
public class MyTest04 {
public static void main(String[] args) throws InterruptedException {
Long start = System.currentTimeMillis();
final Random random = new Random();
final List<Integer> list = new ArrayList<>();
ExecutorService executorService = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10000; i++){
executorService.execute(new Runnable() {
@Override
public void run() {
list.add(random.nextInt());
}
});
}
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.DAYS);
System.out.println("时间:" + (System.currentTimeMillis()-start));
System.out.println("大小" + list.size());
}
}
使用线程池的好处
- 通过重复利用已创建的线程降低线程创建和销毁造成的消耗
- 当任务到达时,任务可以不需要的等到线程创建就能立即执行
- 线程是稀缺资源,如果无限制的创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,调优和监控。