1.线程简介
2.线程创建(Thread、Runnable、Callable)
- 三种创建方法
- 继承Thread
- 自定义线程类继承Thread类
- 重写run() 方法,编写线程执行体
- 创建线程对象,调用start() 方法启动线程
- 不建议使用:避免OOP单继承局限性
public class TestThread extends Thread {
@Override
public void run() {
// run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("check code " + i);
}
}
public static void main(String[] args) {
// main线程,主线程
// 创建一个线程对象
TestThread thread = new TestThread();
// 调用start()方法开启线程
thread.start();
for (int i = 0; i < 20; i++) {
System.out.println("learn thread " + i);
}
}
}
- 实现Runnable
- 定义MyRunnable类实现Runnable接口
- 实现run() 方法,编写线程执行体
- 创建线程对象,调用start() 方法启动线程
- 推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
public class TestThread implements Runnable {
@Override
public void run() {
// run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("check code " + i);
}
}
public static void main(String[] args) {
// 创建Runnable接口的实现类对象
TestThread testThread = new TestThread();
// 创建线程对象,通过线程对象来开启我们的线程,代理
new Thread(testThread).start();
for (int i = 0; i < 20; i++) {
System.out.println("learn thread " + i);
}
}
}
public class Race implements Runnable {
private static String winner;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
// 模拟兔子睡觉
String threadName = Thread.currentThread().getName();
if ("兔子".equals(threadName) && i % 20 == 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 判断比赛是否结束
boolean flag = gameOver(i);
if (flag) {
break;
}
System.out.println(threadName + "-->跑了" + i + "步");
}
}
private boolean gameOver(int steps) {
// 判断是否由胜利者
if (winner != null) {
return true;
} else if (steps == 100) {
winner = Thread.currentThread().getName();
System.out.println("winner is " + winner);
return true;
} else {
return false;
}
}
public static void main(String[] args) {
Race race = new Race();
new Thread(race, "兔子").start();
new Thread(race, "乌龟").start();
}
}
- 实现Callable
- 实现Callable接口,需要返回值类型
- 重写call方法,需要抛出异常
- 创建目标对象
public class TestCallable implements Callable {
private String name;
private TestCallable(String name) {
this.name = name;
}
@Override
public Boolean call() {
System.out.println("check code " + name);
return true;
}
public static void main(String[] args) {
TestCallable c1 = new TestCallable("a");
TestCallable c2 = new TestCallable("b");
TestCallable c3 = new TestCallable("c");
// 创建执行服务
ExecutorService service = Executors.newFixedThreadPool(3);
// 提交执行
Future s1 = service.submit(c1);
Future s2 = service.submit(c2);
Future s3 = service.submit(c3);
// 获取结果
try {
Boolean b1 = s1.get();
Boolean b2 = s2.get();
Boolean b3 = s3.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
// 关闭服务
service.shutdownNow();
}
}