Java多线程详解


基本使用

实现Runnable接口

实现Runnable的run方法

1
2
3
4
5
6
7
public class TestRunnable implements Runnable{
@Override
public void run() {
System.out.println("test");
}
}

通过Thread的start方法启动线程

1
2
3
4
5
public static void main(String[] args) {
TestRunnable testRunnable = new TestRunnable();
Thread thread = new Thread(testRunnable);
thread.start();
}

实现Callable接口

实现Callable的call方法

1
2
3
4
5
6
7
public class TestCallable implements Callable<String> {
@Override
public String call() {
String res = "test";
return res;
}
}

Callnable使用多线程可以有返回值,通过FutureTask封装

1
2
3
4
5
6
7
8
9
10
11
12
public static void main(String[] args) {
TestCallable testCallable = new TestCallable();
FutureTask<String> futureTask = new FutureTask<>(testCallable);
Thread thread = new Thread(futureTask);
thread.start();
try {
String res = futureTask.get();
System.out.println(res);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}

继承Thread类

重写run方法,因为Thread实现了Runnable接口

1
2
3
4
5
public class TestThread extends Thread{
public void run() {
System.out.println("test");
}
}

调用start方法启动线程

1
2
3
4
public static void main(String[] args) {
TestThread testThread = new TestThread();
testThread.start();
}

线程池

CachedThreadPool

1
2
3
4
5
6
7
8
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
executorService.execute(new TestRunnable());
}
executorService.shutdown();
}

线程主要方法

sleep()

休眠当前线程,被中断会抛出InterruptedException

1
2
3
4
5
6
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

yield()

建议线程调度器让相同优先级的其它线程优先运行

1
Thread.yield();

← Prev 日期工具类 | Redis常见问题总结 Next →