线程
进程
进程是系统进行资源分配和调用的独立单元,每一个进程都有它的”独立”内存空间和系统资源。
线程
线程是进程里面的一条执行路径,每个线程同享进程里面的内存空间和系统资源
一个进程 – 多线程:各个线程都有不同的分工
线程和进程的关系
进程:进程之间的内存空间和系统资源是独立的
线程:线程之间是共享内存空间和系统资源的
进程中:可以有一条或一条以上的线程
- 进程里只有一条线程的情况下,这条线程就叫做主线程
- 进程里有多条线程的情况下,只有一条线程叫做主线程
- 线程是在进程里的,他们是包裹关系
创建线程
- 创建一个自己的线程类,继承Thread,重写run方法
- 创建一个自己的任务类,实现Runnable接口,重写run方法
- 创建带有返回值的线程,实现Callable接口,重写call(),(结合线程池使用)
方式1:
public class MyThread extends Thread{
@Override
public void run() {
System.out.println(this.getName() + " - 子线程运行run方法~");
}
}
public class Test01 {
public static void main(String[] args) {
/**
* 知识点:创建线程 - 线程类的方式
*/
//创建线程
MyThread t = new MyThread();
//启动线程
t.start();
}
}
方式2:
public class Task implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " - 子线程运行run方法~");
}
}
public class Test01 {
public static void main(String[] args) {
/**
* 知识点:创建线程 - 任务类的方式
*/
//创建任务类对象
Task task = new Task();
//创建线程
Thread t = new Thread(task);
//启动线程
t.start();
}
}
总结
创建线程类和创建任务类线程的区别:
- 创建线程类:编写简单,无需使用Thread.currentThread()方法,直接使用this,即可获得当前线程。
- 创建任务类:可以多个线程共享同一个目标对象,所以非常适合多个相同线程来处理同一份资源的情况,从而可以将CPU代码和数据分开,形成清晰的模型,较好地体现了面向对象的思想。如果需要访问当前线程,必须使用Thread.currentThread()方法。
经典面试题:请问当我们编写一个单纯的main方法时,此时该程序是否为单线程的?为什么?
答:也是多线程, 垃圾回收器也是一个线程
线程的优先级别
public class Test01 {
public static void main(String[] args) {
/**
* 知识点:线程的优先级别
*
* 需求:在主线程中创2个子线程,并且设置不同优先级,观察其优先级对线程执行结果的”影响”。
*/
//创建线程
A a = new A();
B b = new B();
//设置优先级别(1~10)
a.setPriority(Thread.MAX_PRIORITY);//10
b.setPriority(Thread.NORM_PRIORITY);//5
//b.setPriority(Thread.MIN_PRIORITY);//1
//启动线程
a.start();
b.start();
}
}
public class A extends Thread{
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println("A:" + i);
}
}
}
public class B extends Thread{
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println("B:" + i);
}
}
}
总结
优先级高的一般会优先执行,但只是概率性,并不是绝对的
线程的休眠 sleep
sleep方法是静态方法,直接用类名调用,关键是这个方法休眠的是哪个线程?(答:写在哪个线程,就休眠哪个线程)
public class MyThread extends Thread{
public MyThread(String name) {
super(name);
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
// System.out.println(super.getName() + ":" + i);
//获取当前线程的对象
// Thread t = Thread.currentThread();
// String name = t.getName();
// System.out.println(name + ":" + i);
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
public class Test02 {
public static void main(String[] args) throws InterruptedException {
/**
* 知识点:让线程休眠
*
* 需求:编写一个抽取学员回答问题的程序,要求倒数三秒后输出被抽中的学员姓名
*/
Random ran = new Random();
String[] arr = {"aaa","bbb","ccc","sss","xxx","yyy","fff"};
int cnt = ran.nextInt(arr.length);
for (int i = 3; i > 0; i--) {
System.out.println(i);
Thread.sleep(1000);
}
System.out.println(arr[cnt]);
}
}
线程的礼让 yield
礼让:暂停当前正在执行的线程对象,并执行其他线程。
public class Test01 {
public static void main(String[] args) {
/**
* 知识点:线程礼让 - yield()
*
* 需求:创建两个线程A,B,分别各打印1-100的数字,其中B一个线程,每打印一次,就礼让一次,观察实验结果
*/
A a = new A();
B b = new B();
a.start();
b.start();
}
}
public class A extends Thread{
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println("A:" + i);
}
}
}
public class B extends Thread{
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println("B:" + i);
Thread.yield();
}
}
}
线程的合并 join
主线程和子线程同时运行,满足一定条件后,让子线程先运行至结束
public class Test01 {
public static void main(String[] args) throws InterruptedException {
/**
* 知识点:线程的合并 - join
*
* 需求:主线程和子线程各打印100次,从1开始每次增加1,
* 当主线程打印到10之后,让子线程先打印完再打印主线程
*/
MyThread t = new MyThread();
t.start();
for (int i = 1; i <= 100; i++) {
System.out.println("主线程:" + i);
if(i == 10){
t.join();
}
}
}
}
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println("子线程:" + i);
}
}
}
线程的中断
public class Test01 {
public static void main(String[] args) throws InterruptedException {
/**
* 知识点:线程的中断
*/
MyThread t = new MyThread();
t.start();
Thread.sleep(1);
//改变线程的状态--->true
t.interrupt();
}
}
public class MyThread extends Thread {
@Override
public void run() {
//isInterrupted() - 获取当前线程的状态(true-中断 false-存活)
while(!Thread.currentThread().isInterrupted()){
System.out.println();
System.out.println("111");
System.out.println("222");
System.out.println("333");
System.out.println("444");
}
}
}
守护线程
public class Test01 {
public static void main(String[] args) throws InterruptedException {
/**
* 知识点:后台线程/守护线程
*/
GuardThread guardThread = new GuardThread();
guardThread.setDaemon(true);//将此线程设置为后台线程
guardThread.start();
for (int i = 1; i <=5; i++) {
System.out.println("前台线程:" + i);
Thread.sleep(1000);
}
}
}
public class GuardThread extends Thread{
@Override
public void run() {
while(true){
System.out.println("守护线程默默守护着前台线程...");
//父类run方法没有抛异常,子类重写后也不能抛异常
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
线程的生命周期
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-W8iE08fE-1630310084893)(%E7%BA%BF%E7%A8%8B%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F.png)]
线程的生命周期(五种状态):创建 --> 就绪 --> (阻塞)–> 运行 --> 死亡
注意:调用start() 只是进入到就绪状态,调用run()时线程才是运行状态
线程局部变量
实现线程范围内的共享变量:把变量共享给run方法里所有的对象
1.使用 ConcurrentHashMap 共享单个变量
public class Test01 {
public static ConcurrentHashMap<Thread, Integer> map = new ConcurrentHashMap<>();
public static void main(String[] args) {
new Thread( new Runnable() {
@Override
public void run() {
int i = 10;
map.put(Thread.currentThread(), i);
A a = new A();
B b = new B();
a.print();
b.print();
}
},"线程1").start();
new Thread(new Runnable() {
@Override
public void run() {
int i = 90;
map.put(Thread.currentThread(), i);
A a = new A();
B b = new B();
a.print();
b.print();
}
},"线程2").start();
}
}
public class A {
public void print(){
Thread thread = Thread.currentThread();
Integer value = Test01.map.get(thread);
System.out.println(thread.getName() + "中的A类对象调用了println() -- " + value);
}
}
public class B {
public void print(){
Thread thread = Thread.currentThread();
Integer value = Test01.map.get(thread);
System.out.println(thread.getName() + "中的B类对象调用了println() -- " + value);
}
}
2.使用 ConcurrentHashMap 共享多个变量
public class Test01 {
public static ConcurrentHashMap<Thread, Data> map = new ConcurrentHashMap<>();
public static void main(String[] args) {
/**
* 共享多个变量的情况
*/
new Thread(new Runnable() {
@Override
public void run() {
Data data = new Data(10,"aaa");
//存数据
map.put(Thread.currentThread(), data);
A a = new A();
B b = new B();
a.println();//10
b.println();//10
}
},"线程1").start();
new Thread(new Runnable() {
@Override
public void run() {
Data data = new Data(20,"bbb");
//存数据
map.put(Thread.currentThread(), data);
A a = new A();
B b = new B();
a.println();//20
b.println();//20
}
},"线程2").start();
}
}
public class A {
public void println(){
Thread thread = Thread.currentThread();
Data value = Test01.map.get(thread);
System.out.println(thread.getName() + "中的A类对象调用了println() -- " + value);
}
}
public class B {
public void println(){
Thread thread = Thread.currentThread();
Data value = Test01.map.get(thread);
System.out.println(thread.getName() + "中的B类对象调用了println() -- " + value);
}
}
//数据包类
public class Data {
private int i;
private String str;
public Data() {
}
public Data(int i, String str) {
this.i = i;
this.str = str;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Data [i=" + i + ", str=" + str + "]";
}
}
3.使用 ThreadLocal 共享多个变量
public class Test01 {
public static ThreadLocal<Data> local = new ThreadLocal<>();
public static void main(String[] args) {
/**
* 共享多个变量的情况 - ThreadLocal
*/
new Thread(new Runnable() {
@Override
public void run() {
Data data = Data.getInstance(10,"aaa");
//存数据
local.set(data);
A a = new A();
B b = new B();
a.println();//10
b.println();//10
}
},"线程1").start();
new Thread(new Runnable() {
@Override
public void run() {
Data data = Data.getInstance(20,"bbb");
//存数据
local.set(data);
A a = new A();
B b = new B();
a.println();//20
b.println();//20
}
},"线程2").start();
}
}
public class A {
public void println(){
Thread thread = Thread.currentThread();
Data value = Test01.local.get();
System.out.println(thread.getName() + "中的A类对象调用了println() -- " + value);
}
}
public class B {
public void println(){
Thread thread = Thread.currentThread();
Data value = Test01.local.get();
System.out.println(thread.getName() + "中的B类对象调用了println() -- " + value);
}
}
多线程
一、使用 线程类 方式解决卖票问题
铁道部发布了一个售票任务,要求销售1000张票,要求有3个窗口来进行销售,请编写多线程程序来模拟这个效果:
窗口001正在销售第1000张票
窗口001正在销售第999张票
窗口002正在销售第998张票
。。。
窗口002正在销售第1张票
- 问题1:三个窗口都卖了1000张票,一共卖了3000张
- 出现原因:三个线程调用三次run方法,就有3*1000张票
- 解决方案:三个线程共用同一个票的变量
- 问题2:有些票卖了重票
- 出现原因:票的输出语句输出后,还没有来得及做票的减减,就被其他线程抢到CPU资源了
- 解决方案:票的输出语句 和 票的减减必须同时执行完毕后,才能被其他线程抢到CPU资源 - 加锁
- 问题3:出现负数
- 出现原因: 票到了零界点(ticket=1),三个线程都进入循环中
- 解决方案:锁中再判断一次
锁对象:多个线程要想互斥住,就必须使用同一把锁
1.synchronized 同步代码块: synchronized(锁对象){//自动上锁 ...要互斥住的代码... }//自动解锁 同步方法: //锁对象:this(锁对象不唯一,导致卖票重复) public synchronized void method01(){//自动上锁 ...要互斥住的代码... }//自动解锁 //锁对象:类的字节码文件对象 public static synchronized void method02(){//自动上锁 ...要互斥住的代码... }//自动解锁 2.Lock 调用 lock();//手动上锁 ...要互斥住的代码... 调用 unlock();//手动解锁
1、synchronized 作用在代码块上
public class Test01 {
public static void main(String[] args) {
MyThread t1 = new MyThread("窗口一");
MyThread t2 = new MyThread("窗口二");
MyThread t3 = new MyThread("窗口三");
t1.start();
t2.start();
t3.start();
}
}
public class MyThread extends Thread{
private static int ticket = 1000;
private static Object o = new Object();
public MyThread(String name) {
super(name);
}
@Override
public void run() {
while(ticket > 0){
// synchronized("abc"){
// synchronized(Character.class){
synchronized (o) {
if (ticket >0) {
System.out.println(Thread.currentThread().getName() + "正在卖第" + ticket + "张票");
ticket--;
}
if (ticket <= 0) {
System.out.println(Thread.currentThread().getName() + "的票已售完!");
}
}
}
}
}
2、synchronized 作用在方法上
public class Test01 {
public static void main(String[] args) {
MyThread t1 = new MyThread("窗口001");
MyThread t2 = new MyThread("窗口002");
MyThread t3 = new MyThread("窗口003");
t1.start();
t2.start();
t3.start();
}
}
public class MyThread extends Thread{
private static int ticket = 1000;
public MyThread(String name) {
super(name);
}
@Override
public void run() {
while(ticket > 0){
method02();
// method01();
}
}
//锁对象:类的字节码文件对象(MyThread.class)
public static synchronized void method02(){
if(ticket > 0){
System.out.println(Thread.currentThread().getName() + "正在销售第" + ticket + "张票");
ticket--;
}
if(ticket <= 0){
System.out.println(Thread.currentThread().getName() + "票已售完!");
}
}
//锁对象:this 锁对象不唯一,导致卖票重复
public synchronized void method01(){
if(ticket > 0){
System.out.println(Thread.currentThread().getName() + "正在销售第" + ticket + "张票");
ticket--;
}
if(ticket <= 0){
System.out.println(Thread.currentThread().getName() + "票已售完!");
}
}
}
3、使用 ReentrantLock 锁
public class MyThread extends Thread{
private static int ticket = 1000;
private static Lock lock = new ReentrantLock();
public MyThread(String name) {
super(name);
}
@Override
public void run() {
while(ticket > 0){
lock.lock();//手动上锁
if(ticket > 0){
System.out.println(Thread.currentThread().getName() + "正在销售第" + ticket + "张票");
ticket--;
}
if(ticket <= 0){
System.out.println(Thread.currentThread().getName() + "票已售完");
}
lock.unlock();//手动解锁
}
}
}
二、使用 任务类 方式解决卖票问题
1、synchronized 作用在代码块上
public class Test01 {
public static void main(String[] args) {
Task task = new Task();
Thread t1 = new Thread(task, "窗口一");
Thread t2 = new Thread(task, "窗口二");
Thread t3 = new Thread(task, "窗口三");
t1.start();
t2.start();
t3.start();
}
}
public class Task implements Runnable{
private int ticket = 1000;
private static Object obj1 = new Object();
private Object obj2 = new Object();
@Override
public void run() {
while(ticket > 0){
// synchronized ("abc") {
// synchronized (Byte.class) {
// synchronized (obj1) {
synchronized (obj2) {
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "正在卖第" + ticket + "张票");
ticket--;
}
if(ticket <= 0){
System.out.println(Thread.currentThread().getName() + "票已售完!");
}
}
}
}
}
2、synchronized 作用在方法上
public class Task implements Runnable{
private int ticket = 1000;
@Override
public void run() {
while(ticket > 0){
method();
}
}
//锁对象:this
public synchronized void method(){
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "正在卖第" + ticket + "张票");
ticket--;
}
if(ticket <= 0){
System.out.println(Thread.currentThread().getName() + "票已售完!");
}
}
}
3、使用 lock 锁
public class Task implements Runnable{
private int ticket = 1000;
private Lock lock = new ReentrantLock();
// private static Lock lock = new ReentrantLock(); //加static后,锁对象唯一,进行多任务时,只能执行到一个任务
@Override
public void run() {
while(ticket > 0){
lock.lock();
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "正在卖第" + ticket + "张票");
ticket--;
}
if(ticket <= 0){
System.out.println(Thread.currentThread().getName() + "票已售完!");
}
lock.unlock();
}
}
}