目录:
1.进程与线程的概念
2.Java多线程实现
2.1继承Thread类实现多线程
2.2实现Runnable接口来实现多线程
2.3继承Thread类与实现Runnable接口的关系
2.4实现Callable<V>实现多线程
3.多线程常用操作方法
3.1线程的命名与取得
3.2线程休眠方法sleep
3.3线程让步方法yield
3.4等待其他线程终止方法join
3.5线程终止
3.6线程优先级
3.7守护线程
1.进程与线程的概念
进程:操作系统中一个程序的执行周期
线程:一个进程同时执行多个任务。通常来讲,每一个任务就称为一个线程。(进程中的每一个子任务)
进程与线程的比较:
1.1与进程相比,线程更加的“轻量级”,创建、撤销一个线程比启动、撤销一个进程开销要小的多。一个进程中的所有线程共享此进程的所有资源。
1.2没有进程就没有线程,进程一旦终止,其内的线程也将不复存在
1.3进程是操作系统资源调度的基本单位,进程可以独享资源;线程需要依托进程提供资源,无法独立申请操作系统资源,是OS任务执行的基本单位。
JVM是一个进程,主方法是其中的一个线程,称为主线程。
当用Java虚拟机启动JVM虚拟机时,就是启动了一个主进程。
在实际应用中,多线程非常有用。例如:一个浏览器应用可以同时下载多个图片、音乐;一个Web服务器需要同时处理多个并发的请求。
高并发:访问的线程量非常非常高。
高并发带来的问题:服务器内存不够用,无法处理新的请求。
2.Java多线程实现
2.1继承Thread类实现多线程
java.long.Thread是线程操作的核心类。新建一个线程最简单的方法就是直接继承Thread,而后覆写run()方法(相当于主线程的main()方法)。
class MyThread extends Thread{ //线程主体类
private String title;
public MyThread(String title) {
this.title = title;
}
@Override
public void run() {
for(int i=0; i<3; i++){
System.out.println(this.title+",i="+i);
}
}
}
public class Test2{
public static void main(String[] args) {
MyThread myThread1 = new MyThread("myThread1");
MyThread myThread2 = new MyThread("myThread2");
MyThread myThread3 = new MyThread("myThread3");
myThread1.run();
myThread2.run();
myThread3.run();
}
}
这个时候只是做了一个顺序打印,和多线程一点关系都没有。正确启动多线程的方式是调用Thread类的start()方法。
class MyThread extends Thread{ //线程主体类
private String title;
public MyThread(String title) {
this.title = title;
}
@Override
public void run() {
for(int i=0; i<200; i++){
System.out.println(this.title+",i="+i);
}
}
}
public class Test2{
public static void main(String[] args) {
MyThread myThread1 = new MyThread("myThread1");
MyThread myThread2 = new MyThread("myThread2");
MyThread myThread3 = new MyThread("myThread3");
myThread1.start();
myThread2.start();
myThread3.start();
}
}
无论哪种方式实现多线程,线程启动一定调用Thread类提供的start()方法!如果用户自己直接调用run()方法,则为普通方法。
线程的start方法只能调用一次,多次调用则会产生java.long.IllegalThreadStateException(线程状态异常),第一次启动后已经进入就绪状态,再次调用时,线程的状态已经不是0,所以会抛异常。
线程的调度过程:
![]()
start()方法是一个只声明而未实现的方法同时使用native关键字进行定义。
即:start(Java方法)-> start0(本地方法,JVM)->进行资源调度,系统分配(JVM)->run(Java方法)执行线程的具体操作任务
2.2实现Runnable接口来实现多线程
Thread类的核心功能是进行线程的启动,如果一个类为了实现多线程直接去继承Thread类就会有单继承权限。在Java中有提供另外一种实现模式:Runnable接口。(接口优先原则)
此时MyThread类继承的不在是Thread类而实现了Runnable接口,虽然解决的单继承局限的问题,但是没有start()方法被继承了。在看看Thread类提供的构造方法。
无论何种方式,启动线程必须使用Thread类提供放入start()方法。
class MyThread implements Runnable{ //线程主体类
private String title;
public MyThread(String title) {
this.title = title;
}
@Override
public void run() {
for(int i=0; i<200; i++){
System.out.println(this.title+",i="+i);
}
}
}
public class Test1{
public static void main(String[] args) {
MyThread myThread1 = new MyThread("myThread1");
MyThread myThread2 = new MyThread("myThread2");
MyThread myThread3 = new MyThread("myThread3");
new Thread(myThread1).start();
new Thread(myThread2).start();
new Thread(myThread3).start();
}
}
//使用匿名内部类创建Runnable对象
public class Test1{
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hello world");
}
}).start();
}
}
//使用Lambda表达式创建Runnable对象
public class Test1{
public static void main(String[] args) {
Runnable runnable = () -> System.out.println("hello");
new Thread(runnable).start();
}
}
2.3继承Thread类与实现Runnable接口的关系
public class Thread implements Runnable
I. Thread类与自定义线程类MyThread(实现了Runnable接口),是一个典型的代理设计模式。(一个接口两个子类)
Thread类负责 辅助真实业务操作(资源调度,创建线程并启动)
自定义线程类负责真实业务的实现(run方法具体要做啥事)
II.使用Runnable接口实现的多线程程序类可以更好的描述共享的概念。
例:使用Thread实现数据共享(产生若干线程进行同一数据的处理操作)
class MyThread extends Thread {
private int ticket = 5 ; // 一共10张票
@Override
public void run() {
while(this.ticket>0){
System.out.println("剩余票数:"+this.ticket -- );
}
}
}
public class Test2 {
public static void main(String[] args) {
MyThread mt = new MyThread();
new MyThread().start();
new MyThread().start();
new MyThread().start();
}
}
此时启动三个线程实现卖票处理,结果变为了卖各自的票。
例:使用Runnable实现数据共享
class MyThread implements Runnable{
private Integer ticket = 10;
private String title;
public MyThread(String title) {
this.title = title;
}
public void run(){
for(int i=0; i<10; i++){
System.out.println(this.title+"、还剩下"+this.ticket--+"票");
}
}
}
public class Test1{
public static void main(String[] args) {
MyThread mt = new MyThread("黄牛");
Thread thread1 = new Thread(mt);
Thread thread2 = new Thread(mt);
Thread thread3 = new Thread(mt);
thread1.start();
thread2.start();
thread3.start();
}
}
2.4实现Callable<V>实现多线程(juc)-当线程有返回值时只能实现Callable实现多线程, juc-JDK1.5新增的并发程序编程包
java.util.concurrent.Callable<V>
实现Callable接口而后覆写call()方法,有返回值
V call() throws Exception;
Future<V>接口:
V get() throws InterruptedException,ExecutionException;取得Callable接口的返回值。
class MyThread implements Callable<String>{
private Integer ticket = 10;
private String title;
public String call(){
for(int i=0; i<10; i++){
System.out.println("还剩下"+this.ticket--+"票");
}
return "票卖完了~";
}
}
public class Test1{
public static void main(String[] args) {
MyThread myThread = new MyThread();
FutureTask<String> futureTask = new FutureTask<>(myThread);
Thread thread = new Thread(futureTask);
Thread thread1 = new Thread(futureTask);
thread.start();
thread1.start();
try {
System.out.println(futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
3.多线程常用操作方法
3.1线程的命名与取得
I.通过构造方法在创建线程时设置线程名称
public Thread(String name)
public Thread(Runnable target, String name)
II.取得线程名称
public final String getName()
III.在创建线程之后设置线程名称
public final synchronized void setName(String name)
如果不设置名字。系统默认为Thread-0;
例:证明主方法是一个线程
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
public class Test1{
public static void main(String[] args) {
Thread thread = new Thread((new MyThread()));
thread.run();
}
}
3.2线程休眠方法sleep(long time)-单位为毫秒(1000毫秒为1秒) running(运行状态)->blocked(阻塞状态)
线程休眠:让当前线程暂缓执行,等到了预计时间后在恢复执行。
线程休眠会交出CPU,但是不会释放锁。(立马交出CPU)
休眠时间结束后blocked(阻塞状态)->runnable(就绪状态),线程不是立马执行,看系统调度。(系统调度一定是随机的)
class MyThread implements Runnable{
@Override
public void run() {
for(int i=0; i<3; i++){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"、"+i);
}
}
}
public class Test1{
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread,"A");
Thread thread1 = new Thread(myThread,"B");
Thread thread2 = new Thread(myThread,"C");
thread.start();
thread1.start();
thread2.start();
}
}
3.3线程让步(yield()方法) running(运行状态)->runnable(就绪状态)
暂停执行当前的线程对象,并执行其他的线程。
yield()方法会让当前线程交出CPU,同样不会释放锁。但是yield()方法无法控制具体交出CPU的时间,并且yield()方法只能让拥有相同优先级的线程有获取CPU的机会。(yield不会立马交出CPU)
class MyThread implements Runnable{
@Override
public void run() {
for(int i=0; i<3; i++){
Thread.yield();
System.out.println(Thread.currentThread().getName()+"、"+i);
}
}
}
public class Test1 {
public static void main(String[] args) {
MyThread myThread = new MyThread();
new Thread(myThread).start();
new Thread(myThread).start();
new Thread(myThread).start();
}
}
3.4等待其他线程终止。 join()
join方法只是对Object提供的wait()做了一层包装而已
运行态到阻塞态,在从阻塞状态回到就绪状态
等待该线程终止。如果在主线程中调用该方法,会让主线程睡眠,让调用该方法的线程先执行完毕后在恢复执行主线程。
join(),会释放对象锁,join()线程执行完毕,阻塞解除
class MyThread implements Runnable{
@Override
public void run() {
for(int i=0; i<3; i++){
System.out.println(Thread.currentThread().getName()+"、"+i);
}
}
}
public class Test1 {
public static void main(String[] args) {
System.out.println("main线程开始");
MyThread myThread = new MyThread();
new Thread(myThread,"子线程A").start();
System.out.println("main线程结束");
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println("主线程休眠开始");
Test1.printTime();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程休眠结束");
Test1.printTime();
}
}
public class Test1 {
public static void main(String[] args) {
System.out.println("main线程开始");
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread, "子线程A");
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main线程结束");
}
public static void printTime() {
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = dateFormat.format(date);
System.out.println(str);
}
}
3.5线程停止
3.5.1设置标志位停止线程(重要)
class MyThread implements Runnable{
private boolean flag = true;
@Override
public void run() {
int i = 1;
while(flag){
try {
Thread.sleep(1000);
System.out.println("子线程第"+i+"次执行...");
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
}
}
public void setFlag(boolean flag){
this.flag = flag;
}
}
public class Test1 {
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread, "子线程A");
thread.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
myThread.setFlag(false);
}
}
3.5.2调用Thread类的stop方法强制停止线程。该方法不安全已经被Deprecated(废弃)
public class Test1{
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
Thread thread1 = new Thread(myThread,"子线程A");
thread1.start();
Thread.sleep(5000);
thread1.stop();
}
}
3.5.3调用Thread类的interrupt()方法
interrupt()方法只是将线程状态置为中断状态而已,它不会中断一个正在运行的线程。此方法只是给线程传递一个中断信号,程序可以根据此信号来判断是否需要终止。
class MyThread implements Runnable{
@Override
public void run() {
int i = 1;
while(true){
boolean bool = Thread.currentThread().isInterrupted();
System.out.println(Thread.currentThread().getName()+"第"+i+"次执行");
System.out.println(bool);
if(bool){
System.out.println("线程退出...");
break;
}
i++;
}
}
}
public class Test1{
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
Thread thread1 = new Thread(myThread,"子线程A");
thread1.start();
Thread.sleep(1000);
thread1.interrupt();
}
}
当线程中使用了wait、sleep以及join方法导致此线程阻塞,则interrupt()会在线程中抛出InterruptException,并且将线程的中断状态由true置为false。
class MyThread implements Runnable{
@Override
public void run() {
int i = 1;
while(true){
try {
Thread.sleep(1000);
boolean bool = Thread.currentThread().isInterrupted();
if(bool){
System.out.println("线程退出...");
break;
}
System.out.println(Thread.currentThread().getName()+"第"+i+"次执行");
System.out.println(bool);
i++;
} catch (InterruptedException e) {
System.out.println("异常抛出,线程停止");
boolean bool = Thread.currentThread().isInterrupted();
System.out.println("Catch块中中断状态为"+bool);
return;
}
}
}
}
3.6线程优先级
线程优先级是指优先级越高越有可能先执行,但仅仅是有可能而已。
设置优先级:
public final void setPriority(int newPriority)
取得优先级:
public final int getPriority()
静态属性,用类名调用:
MAX_PRIORITY = 10;
NORM_PRIORITY = 5;
MIN_PRIORITY = 1;
class MyThread implements Runnable{
@Override
public void run() {
for(int i=0; i<2; i++){
System.out.println(Thread.currentThread().getName()+"、"+i);
}
}
}
public class Test1{
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
Thread thread1 = new Thread(myThread,"子线程A");
Thread thread2 = new Thread(myThread,"子线程B");
Thread thread3 = new Thread(myThread,"子线程C");
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.NORM_PRIORITY);
thread3.setPriority(Thread.MIN_PRIORITY);
thread1.start();
thread2.start();
thread3.start();
}
}
主线程只是一个普通优先级而已。
System.out.println(Thread.currentThread().getName()+
" "+Thread.currentThread().getPriority());
线程具有继承性:只是继承优先级而已。
从A线程启动B线程,则B和A的优先级是一样的。
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+
" "+Thread.currentThread().getPriority());
Thread thread = new Thread(new B(),"子线程B");
thread.start();
}
}
class B implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+
" "+Thread.currentThread().getPriority());
}
}
public class Test1{
public static void main(String[] args) throws InterruptedException {
System.out.println(Thread.currentThread().getName()+
" "+Thread.currentThread().getPriority());
Thread thread = new Thread(new MyThread(),"子线程A");
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();
}
}
3.7守护线程
守护线程是一种特殊的线程,又称为陪伴线程。Java中一共有两种线程:用户线程与守护线程。
Thread类提供的isDaemon()区别两种线程:返回false表示该进程为用户线程;否则为守护线程。典型守护线程就是垃圾回收线程。
只要已启动JVM就会有两个线程,主线程和垃圾回收线程。
只要当前JVM进程中存在任何一个用户线程没有结束,守护进程就在工作;只有当最后一个用户进程结束时,守护进程才会随着JVM一同停止工作。
Thread提供setDaemon()将用户线程设置为守护进程。
class MyThread implements Runnable{
@Override
public void run() {
while(true){
System.out.println(Thread.currentThread().getName()+"当前是否为守护线程"
+Thread.currentThread().isDaemon());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName());
System.out.println("线程退出");
return;
}
}
}
}
public class Test1{
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
Thread thread1 = new Thread(myThread,"子线程A");
//将thread1设置为守护线程
thread1.setDaemon(true);
Thread thread2 = new Thread(myThread,"子线程B");
thread1.start();
thread2.start();
Thread.sleep(3000);
thread2.interrupt();
}
}