- 线程简介
- 普通方法调用和多线程
- 线程创建
- Thread类
- Runnable接口
- Callable接口
- 线程状态
- 线程停止
- 线程休眠
- 线程礼让
- 线程强制执行
- 线程状态观测
- 线程优先级
- 守护线程
- 线程同步
- 同步方法
- 死锁
- Lock锁
程序时指令和数据的有数集合,其本身没有任何运行的含义,是一个静态的概念。进程则是执行程序的一次执行过程,是一个动态的概念,是系统资源分配的单位。
一个进程中通常会有若干个线程,一个进程中至少有一个线程,不然没有存在的意义,线程是CPU调度和执行的单位。
线程就是独立的执行路径。
在程序运行时即使自己没有创建线程,后台也会有多个线程。main()是主线程,为系统的入口,用于执行整个程序。
在一个进程中,如果开辟了多个线程,线程的运行由调度器安排调度。调度器是与操作系统紧密相关的,先后顺序不能人为的干预。
对同一份资源操作时,会存在资源抢夺的问题,需要加入并发控制,
线程会带来额外的开销,需要加入控制开销。
没个线程在自己的工作内存交互内存控制不当会造成数据不一致。
只有一条主线程时,主线程调用run()方法,多线程出现时,会有多条执行路径,主线程调用start()方法,子线程调用run()方法,多条执行路径,主线程和子线程并行交替执行。
很多的多线程都是模拟出来的真正的多线程指的是有狠多的CPU,即多核,模拟出来的多线程,即在一个CPU的情况下,在同一个时间点,CPU只能执行一个代码,因为切换的很快,所以会有同时执行的错觉。
线程创建有三个创建方式:Thread类,Runable接口,Callable接口。
Thread类Thread类创建线程步骤:自定义线程类继承Thread类,重写run()方法,编写线程执行体,创建线程对象,调用start()方法启动线程。
示例:
package com.kuang;
//创建线程方式一:继承Thread类,重写run方法,调用start开启线程
public class TestThread extends Thread{
@Override
public void run(){
//run线程主体
for (int i=0;i<=20;i++){
System.out.println("我在看代码"+i);
}
}
public static void main(String [] args){
//主线程
//创建一个线程对象
TestThread testThread=new TestThread();
//调用start()方法开启线程
testThread.start();
for(int i=0;i<20;i++){
System.out.println("我在学习"+i);
}
}
}
线程开启不一定立即执行,由CPU进行调度
示例:
下载图片
package com.kuang;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//实现多线程同步下载图片
public class TestThread1 extends Thread{
private String url;
private String name;
TestThread1(String url,String name){
this.url=url;
this.name=name;
}
@Override
public void run(){
WebDownloader webDownloader=new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载文件名:"+name);
}
public static void main(String [] args){
TestThread1 t1=new TestThread1("https://images.nowcoder.com/head/1t.png","1.png");
TestThread1 t2=new TestThread1("https://images.nowcoder.com/head/2t.png","2.png");
TestThread1 t3=new TestThread1("https://images.nowcoder.com/head/3t.png","3.png");
t1.start();
t2.start();
t3.start();
}
}
class WebDownloader{
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
}catch (IOException e){
e.printStackTrace();
System.out.println("IO异常,download方法出现问题");
}
}
}
Runnable接口创建线程的步骤:定义一个类实现Runnable接口,实现run()方法,编写线程执行体,创建线程对象,调用start()方法启动线程。
示例:
package com.kuang;
public class TestThread3 implements Runnable {
@Override
public void run(){
for (int i=0;i<=20;i++){
System.out.println("我在看代码"+i);
}
}
public static void main(String []args){
//创建Runnable类的实现类对象
TestThread3 testThread3=new TestThread3();
//创建线程对象,通过线程对象来开启线程
new Thread(testThread3).start();
for(int i=0;i<20;i++){
System.out.println("我在学习"+i);
}
}
}
实现Runnable接口来创建线程,相对于继承Thread类来创建线程,避免了单继承的局限性,灵活方便,方便同一个对象被多个线程使用。
示例:龟兔赛跑
package com.kuang;
public class Rance implements Runnable{
private static String winner;
@Override
public void run(){
for (int i=0;i<=100;i++){
boolean flag=gameOver(i);
if(flag){
break;
}
System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
}
}
public boolean gameOver(int step){
if(step==100){
return true;
}
return false;
}
public static void main(String [] args){
Rance rance=new Rance();
new Thread(rance,"兔子").start();
new Thread(rance,"乌龟").start();
}
}
Callable接口
Callable接口创建线程的步骤:实现Callable接口,需要返回值类型,然后重写call方法,抛出异常,然后创建目标对象,创建执行服务,之后提交之乡获取结果,最后关闭服务。
创建指向性服务的代码为:
ExecutorService ser= Executors.newFixedThreadPool(3);
提交执行的代码为
Futureresult1=ser.submit(t1);
获取结果的代码为
boolean r1=result1.get()
关闭服务的打代码为
ser.shutdownNow();
示例:
package com.kuang; import java.util.concurrent.*; public class TestCallable implements Callable{ private String url; private String name; TestCallable(String url,String name){ this.url=url; this.name=name; } @Override public Boolean call(){ WebDownloader webDownloader=new WebDownloader(); webDownloader.downloader(url,name); System.out.println("下载文件名:"+name); return true; } public static void main(String [] args) throws ExecutionException, InterruptedException { TestCallable t1=new TestCallable("https://images.nowcoder.com/head/1t.png","1.png"); TestCallable t2=new TestCallable("https://images.nowcoder.com/head/2t.png","2.png"); TestCallable t3=new TestCallable("https://images.nowcoder.com/head/3t.png","3.png"); ExecutorService ser= Executors.newFixedThreadPool(3); Future r1=ser.submit(t1); Future r2=ser.submit(t2); Future r3=ser.submit(t3); boolean re1=r1.get(); boolean re2=r2.get(); boolean re3=r3.get(); System.out.println(re1); System.out.println(re2); System.out.println(re3); ser.shutdownNow(); } }
Callable创建线程的优点是可以有返回值,可以抛出异常
线程状态有:创建状态,就绪状态,阻塞状态,运行状态,死亡状态。
创建状态:线程对象一旦被创建就进入了创建状态
就绪状态:调用了start方法,线程立即进入就绪状态,但不意味着立即调度执行。
运行状态:进入运行状态,线程菜真真的执行线程体的代码快。
死亡状态:线程中断或者结束,一旦进入死亡状态,就不能再次启动。
线程常用的方法
| 方法 | 说明 |
|---|---|
| setPriority(int newPrioity) | 更改线程的优先级 |
| static void sleep(long millis) | 在指定的毫秒数内让当前正在执行的线程休眠 |
| void join() | 等待该线程终止 |
| static void yield() | 暂停当前正在执行的线程对象,并执行其他的线程 |
| void interrupt() | 中断线程,一般别用 |
| boolean isAlive() | 测试线程是否处于活动状态。 |
线程停止不推荐使用JDK提供的stop()和destroy()方法,推荐线程自己停止下来,建议使用一个标志位进行终止变量,当flag=false,则终止线程运行。
示例:
package com.kuang;
public class TestStop implements Runnable{
private boolean flag=true;
@Override
public void run(){
int i=0;
while (flag){
System.out.println("run..with.."+i++);
}
}
public void stop(){
this.flag=false;
}
public static void main(String []args){
TestStop testStop=new TestStop();
new Thread(testStop).start();
for(int i=0;i<1000;i++){
System.out.println("main"+i);
if(i==900){
testStop.stop();
System.out.println("线程停止");
}
}
}
}
线程休眠
线程休眠使用sleep()方法,sleep事件达到后线程进入就绪状态,sleep可以模拟网络延迟,倒计时等,sleep不会释放锁。
线程礼让线程礼让是让当前正在执行的线程暂停,但不阻塞,线程礼让不一定成功。
示例:
package com.kuang;
public class Testyield {
public static void main(String [] args){
MyYield myYield=new MyYield();
new Thread(myYield,"a").start();
new Thread(myYield,"b").start();
}
}
class MyYield implements Runnable{
@Override
public void run(){
System.out.println(Thread.currentThread().getName()+"线程开始执行");
Thread.yield();
System.out.println(Thread.currentThread().getName()+"线程结束");
}
}
Join合并线程,等此线程执行完成后,再执行其他线程,其他线程阻塞。
示例:
package com.kuang;
public class TestJoin implements Runnable{
@Override
public void run(){
for(int i=0;i<100;i++) {
System.out.println("线程vip"+i);
}
}
public static void main(String [] args){
TestJoin testJoin=new TestJoin();
Thread thread=new Thread(testJoin);
for(int i=0;i<500;i++){
if(i==200){
try {
thread.start();
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("main"+i);
}
}
}
线程状态观测
线程状态:
NEW:尚未启动的线程处于此状态
RUNNABLE:在Java虚拟机中执行的线程处于此状态
BLOCKED:被阻塞等待监视器锁定的线程处于此状态
WAITING:正在等待另一个线程执行特定动作的线程处于此状态
TIMED_WAITING:正在等待另一个线程执行动作达到指定等待时间的线程处于此状态
TERMINATED:已退出的线程处于此状态
示例:
package com.kuang;
public class TestState {
public static void main(String [] args) throws InterruptedException {
Thread thread=new Thread(()->{
for(int i=0;i<5;i++){
try{
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
}
System.out.println("");
});
Thread.State state=thread.getState();
System.out.println(state);
thread.start();
state=thread.getState();
System.out.println(state);
while (state!=Thread.State.TERMINATED){
Thread.sleep(100);
state=thread.getState();
System.out.println(state);
}
}
}
线程优先级
Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度按照优先级决定应该调度那个线程来执行。
线程的优先级用数字来表示范围1-10,使用以下方式改变或获取优先级
getPriority()
示例:
package com.kuang;
public class TestPrioerty {
public static void main(String [] args){
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
MyPriierty myPriierty=new MyPriierty();
Thread t1=new Thread(myPriierty);
Thread t2=new Thread(myPriierty);
Thread t3=new Thread(myPriierty);
Thread t4=new Thread(myPriierty);
Thread t5=new Thread(myPriierty);
Thread t6=new Thread(myPriierty);
t1.start();
t2.setPriority(1);
t2.start();
t3.start();
t4.setPriority(4);
t4.start();
t5.start();
t6.setPriority(Thread.MAX_PRIORITY);
t6.start();
}
}
class MyPriierty implements Runnable{
@Override
public void run(){
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
守护线程
线程分为用户线程和守护线程,虚拟机必须确保用户线程执行完毕,虚拟机不用等待守护线程执行完毕,守护线程一般用于记录日志。
示例:
package com.kuang;
public class TestDaemo {
public static void main(String [] args){
GOD god=new GOD();
YOU you=new YOU();
Thread thread=new Thread(god);
thread.setDaemon(true);//默认false是用户线程true为守护线程
thread.start();//守护线程启动
new Thread(you).start();
}
}
class GOD implements Runnable{
@Override
public void run(){
while (true){
System.out.println("GOD");
}
}
}
class YOU implements Runnable{
@Override
public void run(){
for(int i=0;i<1000;i++){
System.out.println("hello word");
}
System.out.println("good bye");
}
}
程序退出,说明虚拟机不会等待守护线程执行完毕后在关闭。
线程同步线程同步指多个线程做同一个资源。
三大线程不安全案例:
1抢票问题
package com.kuang;
public class UnsafeBuyTicket {
public static void main(String [] args){
BuyTicket buyTicket=new BuyTicket();
new Thread(buyTicket,"小明").start();
new Thread(buyTicket,"黄牛").start();
new Thread(buyTicket,"小红").start();
}
}
class BuyTicket implements Runnable{
private int ticket=10;
boolean flag=true;
@Override
public void run(){
while(flag){
buy();
}
}
private void buy(){
if(ticket==0){
flag=false;
return;
}
System.out.println(Thread.currentThread().getName()+"拿到"+ticket--);
}
}
2.银行问题
package com.kuang;
public class UnsafeBank {
public static void main(String [] args){
Account account=new Account(100,"基金");
Drawing you=new Drawing(account,50,"你");
Drawing girlfriend=new Drawing(account,100,"朋友");
you.start();
girlfriend.start();
}
}
class Account{
int money;
String name;
public Account(int money,String name){
this.money=money;
this.name=name;
}
}
class Drawing extends Thread{
Account account;
int drawingMoney;
int nowMoney;
public Drawing(Account account,int drawingMoney,String name){
super(name);
this.account=account;
this.drawingMoney=drawingMoney;
}
@Override
public void run(){
if(account.money-drawingMoney<0){
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.money=account.money-drawingMoney;
nowMoney=nowMoney+drawingMoney;
System.out.println(account.name+"余额为:"+account.money);
System.out.println(this.getName()+"手里的钱"+nowMoney);
}
}
3.线程不安全集合
package com.kuang;
import java.util.ArrayList;
import java.util.List;
public class TestsafeList {
public static void main(String [] args){
List list=new ArrayList<>();
for(int i=0;i<10000;i++){
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
System.out.println(list.size());
}
}
同步方法
我们可以使用synchronizd关键字,包括两种方法synchd()方法和synchrod块,synchrd方法控制对对象的访问,每一个对象对应一把锁,没个synchronized方法都必须后的调用该方法的对象的锁才能执行,否则会出现线程阻塞,方法一旦执行,就会独占该锁,知道该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行,
缺陷:若将一个方法申明synchrd会影响效率。
修复上述的线程安全问题,只需要加上关键字synchronized。
1.买票问题
2.银行问题
package com.kuang;
public class UnsafeBank {
public static void main(String [] args){
Account account=new Account(100,"基金");
Drawing you=new Drawing(account,50,"你");
Drawing girlfriend=new Drawing(account,100,"朋友");
you.start();
girlfriend.start();
}
}
class Account{
int money;
String name;
public Account(int money,String name){
this.money=money;
this.name=name;
}
}
class Drawing extends Thread{
Account account;
int drawingMoney;
int nowMoney;
public Drawing(Account account,int drawingMoney,String name){
super(name);
this.account=account;
this.drawingMoney=drawingMoney;
}
//增加synchized默认锁是this
@Override
public void run(){
synchronized (account){if(account.money-drawingMoney<0){
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.money=account.money-drawingMoney;
nowMoney=nowMoney+drawingMoney;
System.out.println(account.name+"余额为:"+account.money);
System.out.println(this.getName()+"手里的钱"+nowMoney);
}}
}
3.集合问题
package com.kuang;
import java.util.ArrayList;
import java.util.List;
public class TestsafeList {
public static void main(String [] args){
List list=new ArrayList();
for(int i=0;i<10000;i++){
new Thread(()->{
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
死锁
死锁指的是多个线程肚子占用一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或多个线程都在等待对方释放资源,都停止执行的情形。
示例:
package com.kuang;
public class DeadLock {
public static void main(String []args){
MakeUp g1=new MakeUp(0,"小红");
MakeUp g2=new MakeUp(1,"小明");
g1.start();
g2.start();
}
}
class One{
}
class Two{
}
class MakeUp extends Thread{
static One one=new One();
static Two two=new Two();
int choice;//选择
String name;
MakeUp(int choice,String name){
this.choice=choice;
this.name=name;
}
@Override
public void run(){
try{
makeUp();
}catch (InterruptedException e){
e.printStackTrace();
}
}
private void makeUp() throws InterruptedException {
if(choice==0){
synchronized (one){
System.out.println(this.name+"获得口红的锁");
Thread.sleep(1000);
synchronized (two){
System.out.println(this.name+"获得香水的锁");
}
}
}else {
synchronized (two){
System.out.println(this.name+"获得香水的锁");
Thread.sleep(1000);
synchronized (one){
System.out.println(this.name+"获得口红的锁");
}
}
}
}
}
出现了死锁现象
改进
{
static One one=new One();
static Two two=new Two();
int choice;//选择
String name;
MakeUp(int choice,String name){
this.choice=choice;
this.name=name;
}
@Override
public void run(){
try{
makeUp();
}catch (InterruptedException e){
e.printStackTrace();
}
}
private void makeUp() throws InterruptedException {
if(choice==0){
synchronized (one){
System.out.println(this.name+"获得口红的锁");
Thread.sleep(1000);
}
synchronized (two){
System.out.println(this.name+"获得香水的锁");
}
}else {
synchronized (two){
System.out.println(this.name+"获得香水的锁");
Thread.sleep(1000);
}
synchronized (one){
System.out.println(this.name+"获得口红的锁");
}
}
}
}
Lock锁
Lock是显式锁需要手动开启和关闭锁,synchronized是隐式锁,除了作用域自动释放。Lock只有代码块锁,synchronized有代码块和方法锁。Lock锁JVM将花费较少的时间来调度线程,性能更好,并且有着更好的扩展性。



