多线程
什么是线程?
线程是资源调度和分配的基本单位,是运行的最小单位。
什么是多线程?
多线程是指在同一个时间段内有多个线程同时运行。在考虑线程安全的情况时,需要为共享资源进行上锁,注意不能上死锁,否则为进入一个死循环,得不到运行结果。
多线程的五种状态
- 新生
- 就绪
- 运行
- 阻塞
- 终止
如何用代码实现多线程?
- 使用继承Thread类来实现
public class Thread001 extends Thread{
@Override
public void run() {
for(int i = 1;i<=20;i++){
System.out.println("睡觉.....");
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
//创建线程 子类对象
Thread001 th = new Thread001();
//方法的调用,不是线程的开启
//th.run();
//开启线程
th.start();
for(int i = 1;i<=20;i++){
System.out.println("喝水.....");
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
- 实现Runnable接口来实现
public class Thread002 implements Runnable{
@Override
public void run() {
for(int i = 1;i<=20;i++){
System.out.println("一边吃饭.....");
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Thread002 demo = new Thread002();
//1.创建线程
Thread th = new Thread(demo);
//2.开启线程
th.start();
for(int i = 1;i<=20;i++){
System.out.println("一边吃菜.....");
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
- 实现Callable接口来实现
public class Thread003 implements Callable<Integer> {
//记录赢的人的名字 -->共享
private String winner;
/*
定义线程体
*/
@Override
public Integer call() {
//i为步数
for(int i=1;i<=100;i++){
if("pool-1-thread-2".equals(Thread.currentThread().getName()) && i%10==0){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"正在跑第"+i+"步");
//判断游戏是否停止
if(check(i)){
return i;
}
}
return -1;
}
//检查游戏是否终止
//参数: 步数 返回值: boolean true->终止 false->继续
public boolean check(int steps){
if(winner!=null){
return true;
}else if(steps==100){
winner = Thread.currentThread().getName();
return true;
}
return false;
}
public static void main(String[] args) throws Exception{
Thread003 thread003 = new Thread003();
//线程池 ->构建执行 服务
ExecutorService server = Executors.newFixedThreadPool(2);
//提交还行
Future<Integer> fu = server.submit(thread003);
Future<Integer> fu2 = server.submit(thread003);
//获取结果
Integer i1 = fu.get();
Integer i2 = fu2.get();
System.out.println(i1 + "--->"+i2);
//终止执行服务
server.shutdown();
}
}