【JAVA基础篇】多线程

学习Java的多线程知识之前,我们先来了解一下进程和线程的概念,以及他们之间的关系。

进程

基本概念

进程是具有独立功能的程序在某个数据集合上的一次执行过程。

特点

  1. 进程是操作系统进行资源分配的基本单位。
  2. 每个进程都有自己的地址空间,即进程空间。

线程

基本概念

一个进程内部的一个执行单元,它是程序中的一个单一的顺序控制流程。

特点

  1. 自己不拥有系统资源,只拥有一点儿在运行过程中必不可少的资源。与同一个进程下的其他所有线程共享进程所拥有的全部资源。
  2. 线程是进程中的一个实体,是被操作系统独立调度的基本单位。

进程和线程的联系和区别

进程是资源分配的基本单位,线程是调度的基本单位。进程包含线程,线程共用进程的资源。

Java实现多线程

有四种方式:

  1. 继承Thread类
  2. 实现Runnable接口
  3. 实现Callable接口,并与FutureTask结合使用
  4. 线程池

继承Thread类

package com.cc.thread;

public class ThreadDemo extends Thread{
	
	public ThreadDemo(String name) {
		super(name);
	}
	
	@Override
	public void run() {
		for (int i = 0; i < 10000; i++) {
			System.out.println(this.getName()+i);
		}
	}

	public static void main(String[] args) {
		new ThreadDemo("张三").start();
		new ThreadDemo("李四").start();
	}

}

实现Runnable接口

package com.cc.thread;

public class RunableDemo implements Runnable {

	private String name;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public RunableDemo(String name) {
		super();
		this.name = name;
	}

	@Override
	public void run() {
		for (int i = 0; i < 10000; i++) {
			System.out.println(this.getName()+i);
		}

	}

	public static void main(String[] args) {
		new Thread(new RunableDemo("张三")).start();
		new Thread(new RunableDemo("李四")).start();
	}

}

实现Callable接口,并与FutureTask结合使用

package com.cc.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class CallableDemo {

	public static void main(String[] args) {
		CallableImpl callableImpl = new CallableImpl();
		FutureTask<Integer> futureTask = new FutureTask<Integer>(callableImpl);
		Thread thread = new Thread(futureTask);
		thread.start();
		try {
			int sum = futureTask.get();
			System.out.println(sum);
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
	}
	
	private static class CallableImpl implements Callable<Integer>{
		@Override
		public Integer call() throws Exception {
			int sum = 0;
			for (int j = 0; j <= 100; j++) {
				System.out.println(Thread.currentThread().getName()+":"+j);
				sum += j;
			}
			return sum;
		}
	}
		
	
}

运行上面的代码,我们发现每次返回的结果都是5050(这么巧的吗?难道每次call方法瞬间就执行完了,然后再执行的int sum = futureTask.get();),其实如果线程的call方法还未执行完毕,futureTask.get()方法会一直阻塞,直到call()方法执行完毕才能取到返回值。

线程的生命周期

通过查看Thread内部类State的源码,我们知道线程有6中状态,分别是:

    NEW,
    RUNNABLE,
    BLOCKED,
    WAITING,
    TIMED_WAITING,
    TERMINATED;

Thread内部类State的源码

    public enum State {
        /**
         * Thread state for a thread which has not yet started.
         */
        NEW,

        /**
         * Thread state for a runnable thread.  A thread in the runnable
         * state is executing in the Java virtual machine but it may
         * be waiting for other resources from the operating system
         * such as processor.
         */
        RUNNABLE,

        /**
         * Thread state for a thread blocked waiting for a monitor lock.
         * A thread in the blocked state is waiting for a monitor lock
         * to enter a synchronized block/method or
         * reenter a synchronized block/method after calling
         * {@link Object#wait() Object.wait}.
         */
        BLOCKED,

        /**
         * Thread state for a waiting thread.
         * A thread is in the waiting state due to calling one of the
         * following methods:
         * <ul>
         *   <li>{@link Object#wait() Object.wait} with no timeout</li>
         *   <li>{@link #join() Thread.join} with no timeout</li>
         *   <li>{@link LockSupport#park() LockSupport.park}</li>
         * </ul>
         *
         * <p>A thread in the waiting state is waiting for another thread to
         * perform a particular action.
         *
         * For example, a thread that has called <tt>Object.wait()</tt>
         * on an object is waiting for another thread to call
         * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
         * that object. A thread that has called <tt>Thread.join()</tt>
         * is waiting for a specified thread to terminate.
         */
        WAITING,

        /**
         * Thread state for a waiting thread with a specified waiting time.
         * A thread is in the timed waiting state due to calling one of
         * the following methods with a specified positive waiting time:
         * <ul>
         *   <li>{@link #sleep Thread.sleep}</li>
         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
         *   <li>{@link #join(long) Thread.join} with timeout</li>
         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
         *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
         * </ul>
         */
        TIMED_WAITING,

        /**
         * Thread state for a terminated thread.
         * The thread has completed execution.
         */
        TERMINATED;
    }

 关于线程状态的详细描述和他们之前的相互转换请参考4 Java线程的状态及主要转化方法 · 深入浅出Java多线程

线程方法总结

start使线程由新建状态进入就绪状态,只能调用一次,否则会报IllegalThreadStateException
run线程执行体,由系统调用
isAlive新建和死亡状态会返回false,其他状态返回true
interrupt设置线程中断状态为true
interruptedstatic方法,先返回当前线程中断状态,然后设置线程中断状态为false
isInterrupted返回当前线程中断状态
sleepstatic native方法,使线程进入阻塞状态(不会释放同步锁)
currentThreadstatic方法,该方法返回当前正在使用CPU资源的线程
setPriority

final方法,设置线程的优先级,1~10 1最低 10最高 5是默认值

线程的优先级具有继承性,比如A线程启动B线程,则A和B的线程优先级是一样的

getPriorityfinal方法,获取线程优先级
setDaemon设置守护线程(也叫服务线程,用于为系统中的对象和线程提供服务,如果都是服务线程,那么JVM结束,垃圾回收线程是守护线程)
isDaemon判断是否是守护线程
jointhread1.join();使当前线程进入阻塞状态,thread1线程执行完后,再唤醒当前线程
yeild使当前线程进入就绪状态
waitObject类的方法,让当前线程进入阻塞状态,并且释放它持有的同步锁
notifyObject类的方法,唤醒一个阻塞状态的线程
notifyAllObject类的方法,唤醒所有阻塞状态的线程

                                                                                                                                                                                                                                                                                        

join方法的使用

package com.cc.thread;

public class ThreadJoin {

	public static void main(String[] args) throws InterruptedException {
		Thread thread1 = new Thread("线程1"){
			@Override
			public void run() {
				for (int i = 0; i < 1000; i++) {
					System.out.println(Thread.currentThread().getName()+":"+i);
				}
			}
		};
		thread1.start();
		thread1.join();
		for (int i = 0; i < 100; i++) {
			System.out.println(Thread.currentThread().getName()+":"+i);
		}
	}

}

interrupt、interrupted和isInterrupted的作用和区别

  1. interrupt设置线程中断状态为true
  2. interrupted先返回当前线程中断状态,然后设置线程中断状态为false
  3. isInterrupted返回当前线程中断状态
  4. 下面的demo只用到了sleep方法,wait,join方法类似于sleep

package com.cc.thread;
 
public class InterruptTest {

	public static void main(String[] args) throws InterruptedException {
		Thread thread = new Thread() {
			@Override
			public void run() {
				for (int i = 1; i <= 5; i++) {
					try {
						System.out.println(String.format("第%d次循环开始",i));
						sleep(2000);//线程默认中断状态为false,调用sleep方法,或者在sleep的过程中,当中断状态为true时,执行sleep会抛出异常
						interrupt();//设置中断状态为true
						System.out.println(String.format("第%d次循环正常执行,中断状态:%b",i,isInterrupted() ));
					} catch (InterruptedException e) {
						//抛出异常后中断状态自动设置为false
						System.out.println(String.format("第%d次循环出现中断异常,中断状态:%b",i,isInterrupted()));
					}
				}
			}

		};
		thread.start();
	}
}
package com.cc.thread;

public class InterruptTest {

	public static void main(String[] args) throws InterruptedException {
		Thread thread = new Thread(){
			@Override
			public void run() {
				for (int i = 1; i <= 5; i++) {
					try {
						System.out.println(String.format("第%d次循环开始",i));
						sleep(2000);//线程默认中断状态为false,调用sleep方法,或者在sleep的过程中,当中断状态为true时,执行sleep会抛出异常
						interrupt();//设置中断状态为true
						System.out.println("interrupted方法:"+interrupted());//此函数首先返回当前的中断状态,然后将中断状态置为false
						System.out.println(String.format("第%d次循环正常执行,中断状态:%b",i,isInterrupted() ));
					} catch (InterruptedException e) {
						//抛出异常后中断状态自动设置为false
						System.out.println(String.format("第%d次循环出现中断异常,中断状态:%b",i,isInterrupted()));
					}
				}
			}

		};
		thread.start();
	}

}

wait方法的使用

package com.cc.thread;

public class ObjectWait {
 
	public static void main(String[] args) {
		try {
			Thread threadTest = new Thread(){
				public void run(){
					System.out.println("执行线程中方法");
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			};
			threadTest.start();
			synchronized(threadTest){
				threadTest.wait();		//当线程终止的时候,会调用线程自身的notifyAll()方法
			}
			System.out.println("执行到了这里");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

线程安全的概念

什么是线程安全:在多线程环境下,线程安全的代码会通过线程同步机制保证各个线程可以正常的正确的执行,不会出现数据污染等意外情况。

什么是线程同步:是指各个线程按照一定的顺序执行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值