开局小知识:a:(JVM要做很多事情,所以就创建线程来执行main方法-主线程) 每一个应用程序都是一个进程,每个进程都包括多个线程,进程里面任务是它里面的线程执行的
b:面试题:进程里面是不是线程越多越好?不是,计算机开启线程也要耗费资源,这要看任务执行时间,如果cpu调度时间超过了任务执行时间就得不偿失了;
c:并行和并发 eg:你在吃饭,来电话了
并行:一边接电话,一边吃饭(同一个时间多个线程在执行)
并发:先接电话,再吃饭(线程的一个快速切换)
串行:吃完饭,再接电话(它不支持并发,也不支持并行,其实就是单线程)
d: 开启的线程一般是cpu个数的1-3倍;
e:线程执行有优先级,1-10(最大),不设置就是5级,优先级低的只是运行几率比较小;
public final int getPriority()
1. 创建线程的2种方法
一 : 1 定义类继承Thread
2、复写Thread类中的run()
3,调用start()
二 : 1, 定义类实现Runnable接口
2, 复写Runnable接口的run()
3,通过Thread类建立对象,将Runnable接口的子类对象当做实际参数传给Thread类的构造方法(这是因为自定义的run()所属对象是Runnable接口的子类对象,所以要让线程去指定对象的run());
4, start();
实现和继承的区别:实现能避免单继承的局限性(建议实现),实现方式线程代码存放在Runnable接口子类对象的run(),继承方式线程代码存放在Thread类的run()中
2. 操作线程的方法
1. 休眠 Thread.sleep();
2.加入 .join;当加入另一个线程时,另一个线程会等待该线程执行完了再继续执行;
3.礼让 yield();它把资源执行权给别人用(它不知道,cpu来分配)
4.中断 第一种 比较提倡在run()中使用无限循环的形式,然后使用boolean标记控制循环的停止
LoopDemo类
public class LoopDemo implements Runnable { private boolean flag; public void run() { try { while(true) { System.out.println(Thread.currentThread().getName()); if(getFlag()) {//if判断要在while里面 break;//如果是假就打断了。 } } }catch (Exception e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()); } public void setFlag(boolean flag) { this.flag = flag; } public boolean getFlag() { return flag; }}
TestLoop类
public class TestLoop { public static void main(String[] args) { LoopDemo loopDemo = new LoopDemo(); Thread thread = new Thread(loopDemo); thread.start(); System.out.println(Thread.currentThread().getName()); loopDemo.setFlag(true);//true就中断了线程,false就陷入无限循环 }}D:\subline\DuoThread>javac -encoding utf-8 *.javaD:\subline\DuoThread>java TestLoopmainThread-0Thread-0
第二种 使用interrupt中断线程(这个前提条件是线程处于阻塞,休眠,等待状态)
TestInterrupt类
public class TestInterrupt { public static void main(String[] args) { //给线程起名字Thread(Runnable target, String name) Thread thread = new Thread(new InterruptDemo(), "中断线程interrupt"); thread.start(); System.out.println(Thread.currentThread().getName()); try { Thread.sleep(1000);//主线程休眠1秒,thread线程休眠3秒, }catch (Exception e) { e.printStackTrace(); System.out.println(Thread.currentThread().getName()); } thread.interrupt();主线程先醒来继续下面读,读到interrupt就中断thread线程 System.out.println(Thread.currentThread().getName()); }}D:\subline\DuoThread>java TestInterruptmainjava.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method)main at InterruptDemo.run(InterruptDemo.java:6) at java.lang.Thread.run(Thread.java:748)中断线程interrupt中断线程interrupt
InterruptDemo类
public class InterruptDemo implements Runnable { public void run() { try { Thread.sleep(3000); }catch (InterruptedException e) { e.printStackTrace(); System.out.println(Thread.currentThread().getName()); } System.out.println(Thread.currentThread().getName()); }}