用花生棒自己做网站,国外域名查询,云计算存储网站建设安全,阿里百秀 wordpressJava线程
一、线程介绍
程序
是为完成特定任务、用某种语言编写的一组指令的集合#xff08;简单来说就是写的代码#xff09;。
进程
进程是指运行中的程序#xff0c;比如我们使用的QQ#xff0c;就启动了一个进程#xff0c;操作系统会对该进程分配内存空间。当我…Java线程
一、线程介绍
程序
是为完成特定任务、用某种语言编写的一组指令的集合简单来说就是写的代码。
进程
进程是指运行中的程序比如我们使用的QQ就启动了一个进程操作系统会对该进程分配内存空间。当我们使用迅雷又启动了一个进程操作系统将会为迅雷分配内存空间。进程是程序的一次执行过程或是正在运行的一个程序。是动态过程有它自身的产生、存在和消亡的过程。
什么是线程
线程是由进程创建的是进程的一个实体。一个进程可以拥有多个线程就比如迅雷可以同时下载多个文件。
其他相关概念
单线程同一时刻只允许执行一个线程。多线程同一时刻可以执行多个线程比如一个QQ进程可以同时打开多个聊天窗口一个迅雷进程可以同时下载多个文件。并发同一个时刻多个任务交通执行造成一种“貌似同时”的感觉简单的说单核CPU实现的多任务就是并发。 并行同一个时刻多个任务同时执行。多核CPU可以实现并行。并行和并发可能同时存在。 二、线程的使用
2.1 线程的创建
在Java线程创建有两种方式
继承Thread类重写run方法实现Runnable接口重写run方法 2.1.1继承Thread类重写run方法 public class Thread01 {public static void main(String[] args) {Cat cat new Cat();//启动线程最终会执行cat的run方法cat.start();}static class Cat extends Thread {int time 0;Overridepublic void run() {while (true) {System.out.println(喵喵我是小猫咪 (time));try {//线程休眠1秒Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}if (time 8) {break;}}}}
}在main里面建立一个循环此时main线程和main建立的Thread0线程交替执行并发主线程不会阻塞。进程可以创建线程线程也可以创建线程。只有所有线程执行结束进程才会挂掉。 public class Thread01 {public static void main(String[] args) throws InterruptedException {//创建Cat对象可以当做线程使用Cat cat new Cat();cat.start();//启动线程- 最终会执行cat的run方法System.out.println(主线程继续执行 Thread.currentThread().getName());//名字mainfor(int i 0; i 60; i) {System.out.println(主线程 i i);//让主线程休眠Thread.sleep(1000);}}
}class Cat extends Thread {int times 0;Overridepublic void run() {//重写run方法写上自己的业务逻辑while (true) {//该线程每隔1秒。在控制台输出 “喵喵, 我是小猫咪”System.out.println(喵喵, 我是小猫咪 (times) 线程名 Thread.currentThread().getName());//让该线程休眠1秒 ctrlaltttry {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}if(times 80) {break;//当times 到80, 退出while, 这时线程也就退出..}}}
}问题启动线程为什么调用start方法而不是run方法
run方法只是一个普通的方法没有真正的启动一个线程如果调用cat.run()就会把run方法执行完毕后才向下执行串行。
而调用cat.start()会启动线程最终在线程内执行cat的run方法。 外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传
2.1.2 实现Runnable接口重写run方法
Java是单继承的在某些情况下一个类可能已经继承了某一个父类这时候如果想要创建线程只能通过实现接口来创建。 因为Runable接口当中只有run()方法因此不能直接调用start()方法所以需要一个代理完成该方法的调用。
public class Thread02 {public static void main(String[] args) {Dog dog new Dog();//dog.start(); 这里不能调用start//创建了Thread对象把 dog对象(实现Runnable),放入ThreadThread thread new Thread(dog);thread.start();}
}class Dog implements Runnable { //通过实现Runnable接口开发线程int count 0;Overridepublic void run() { //普通方法while (true) {System.out.println(小狗汪汪叫..hi (count) Thread.currentThread().getName());//休眠1秒try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}if (count 10) {break;}}}
}模拟代理
//线程代理类 , 模拟了一个极简的Thread类
class ThreadProxy implements Runnable {//你可以把Proxy类当做 ThreadProxyprivate Runnable target null;//属性类型是 RunnableOverridepublic void run() {if (target ! null) {target.run();//动态绑定运行类型Tiger}}public ThreadProxy(Runnable target) {this.target target;}public void start() {start0();//这个方法时真正实现多线程方法}public void start0() {run();}
}class Animal {
}class Tiger extends Animal implements Runnable {Overridepublic void run() {System.out.println(老虎嗷嗷叫....);}
}public class Thread02 {public static void main(String[] args) {Tiger tiger new Tiger();//实现了 RunnableThreadProxy threadProxy new ThreadProxy(tiger);threadProxy.start();}
}2.2 多线程执行
public class Thread03 {public static void main(String[] args) {T1 t1 new T1();T2 t2 new T2();Thread thread1 new Thread(t1);Thread thread2 new Thread(t2);thread1.start();thread2.start();}
}
class T1 implements Runnable{int count0;Overridepublic void run() {while (true){System.out.println(Thread.currentThread().getName():hello(count));try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}if (count5){break;}}}
}class T2 implements Runnable{int count0;Overridepublic void run() {while (true){System.out.println(Thread.currentThread().getName():hi(count));try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}if (count10){break;}}}
}注意线程全部结束该进程才会结束。
2.3 继承Thread与实现Runnable的区别
从Java的设计来看通过继承Thread或者实现Runnable接口来创建线程本质上没有区别因为Thread类本身就实现了Runnable接口。实现Runnable接口方式更适合多个线程共享一个资源的情况并且避免了单继承限制。
下图程序当中线程thread01和thread02就共享了t3。 2.4 多线程售票问题 public class SellTicket {public static void main(String[] args) {SellTicketByRunnable sellTicketByRunnable new SellTicketByRunnable();new Thread(sellTicketByRunnable).start();//第1个线程-窗口new Thread(sellTicketByRunnable).start();//第2个线程-窗口new Thread(sellTicketByRunnable).start();//第3个线程-窗口}
}class SellTicketByRunnable implements Runnable {//让多个线程共享TICKET_NUMBERprivate static int TICKET_NUMBER 100;Overridepublic void run() {while (true) {if (TICKET_NUMBER 0) {System.out.println(售票结束);break;}try {Thread.sleep(50);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println(窗口 Thread.currentThread().getName() 售出一张票剩余票数 (--TICKET_NUMBER));}}
}可能会出现多售票的情况因为线程不是同步的。
假设剩余一张票三个线程可能同时进去这样会出现多卖问题。
2.5 线程终止
基本说明
当线程完成任务后会自动退出。还可以通过使用变量来控制run方法退出的方式停止线程即通知方式。
应用实例
/*** 线程终止*/
public class ThreadExit {public static void main(String[] args) throws Exception {T t new T();t.start();//让主线程休眠10sThread.sleep(10 * 1000);t.setLoop(false);}
}class T extends Thread {int count 0;//设置一个控制变量Boolean loop true;public void setLoop(Boolean loop) {this.loop loop;}Overridepublic void run() {while (loop) {System.out.println(T正在运行中 (count));try {Thread.sleep(50);} catch (InterruptedException e) {throw new RuntimeException(e);}}}
}三、线程方法
3.1 常用方法第一组
setName()设置线程名称getName()返回该线程的名称start()使该线程开始执行Java虚拟机底层调用该线程的start0()方法run()调用线程对象run方法setPriority()设置线程的优先级getPriority()获取线程的优先级sleep()在指定的毫秒数内让当前正在执行的线程休眠interrupt()中断线程注意不是终止如果线程正在休眠则停止休眠继续执行
public class ThreadMethod01 {public static void main(String[] args) throws Exception {T t new T();t.setName(汤姆);t.setPriority(Thread.MIN_PRIORITY);t.start();//主线程打印5个hi ,然后就中断子线程的休眠for (int i 0; i 5; i) {Thread.sleep(1000);System.out.println(hi i);}System.out.println(t.getName() 线程的优先级 t.getPriority());t.interrupt();}
}class T extends Thread {Overridepublic void run() {while (true) {for (int i 0; i 10; i) {System.out.println(Thread.currentThread().getName() 在学线程.. i);}try {System.out.println(Thread.currentThread().getName() 在休眠中..);Thread.sleep(10000);} catch (InterruptedException e) {//当该线程执行到一个interrupt 方法时就会catch 一个 异常, 可以加入自己的业务代码//InterruptedException 是捕获到一个中断异常System.out.println(Thread.currentThread().getName() 被interrupt了);}}}
}3.2 注意事项和细节 start底层会创建新的线程调用runrun就是一个简单的方法调用不会启动新线程。 线程优先级的范围 interrupt是中断线程但没有真正的结束线程所以一般用于中断正在休眠的线程。 sleep是线程的静态方法使当前线程休眠。
3.3 常用方法第二组
yield线程礼让
让出CPU让其他线程执行但是礼让的时间不确定所以礼让不一定成功。
join线程插队
插队的线程一旦成功则肯定先执行完插入的线程所有的任务后再去执行自己的任务。
案例
主线程和子线程同时吃10个苹果当他们俩都吃到第五个的时候主线程让子线程先吃子线程吃完了主线程再吃。
/*** 线程礼让和插队*/
public class ThreadMethod02 {public static void main(String[] args) throws Exception {T1 t new T1();t.start();for (int i 1; i 10; i) {Thread.sleep(999);System.out.println(主线程吃了 i 个苹果);if (i 5) {System.out.println(子线程插队);//Thread.yield();//主线程礼让不一定成功t.join(); //子线程插队一定成功System.out.println(主线程继续执行);}}}
}class T1 extends Thread {Overridepublic void run() {for (int i 1; i 10; i) {System.out.println(子线程吃了 i 个苹果);try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}}}
}3.4 用户线程和守护线程
用户线程
也叫工作线程当线程的任务执行完或通知方式通知他结束。
守护线程
一般是为了工作线程服务的当所有的工作线程结束守护线程自动结束 。常见的守护线程就是垃圾回收机制。
public class ThreadMethod03 {public static void main(String[] args) throws InterruptedException {MyDaemonThread myDaemonThread new MyDaemonThread();//如果我们希望当main线程结束后子线程自动结束,只需将子线程设为守护线程即可myDaemonThread.setDaemon(true);myDaemonThread.start();for( int i 1; i 10; i) {//main线程System.out.println(宝强在辛苦的工作...);Thread.sleep(1000);}}
}class MyDaemonThread extends Thread {public void run() {for (; ; ) {//无限循环try {Thread.sleep(1000);//休眠1000毫秒} catch (InterruptedException e) {e.printStackTrace();}System.out.println(马蓉和宋喆快乐聊天哈哈哈~~~);}}
}四、线程的生命周期
线程有七种状态
NEWRunnableReady、RunningTimeWaitingWaitingBlockedTeminated public class ThreadState_ {public static void main(String[] args) throws InterruptedException {T t new T();System.out.println(t.getName() 状态 t.getState());t.start();while (Thread.State.TERMINATED ! t.getState()) {System.out.println(t.getName() 状态 t.getState());Thread.sleep(500);}System.out.println(t.getName() 状态 t.getState());}
}class T extends Thread {Overridepublic void run() {while (true) {for (int i 0; i 10; i) {System.out.println(hi i);try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}break;}}
}五、Synchronized
5.1 线程同步机制
在多线程编程一些敏感数据不允许被多个线程同时访问此时就使用同步访问技术保证数据在任何同一时刻最多有一个线程访问以保证数据的完整性。线程同步即当有一个线程在对内存进行操作时其他线程都不可以对这个内存地址进行操作直至该线程完成操作其他线程才能对该内存地址进行操作。
5.2 同步具体方法
同步代码块 synchronized对象{ //得到对象的锁才能操作同步代码//需要被同步代码}同步方法
synchronized还可以放在方法声明中表示整个方法。 public synchronized void mString name{//需要被同步的代码}5.3 使用同步解决售票问题
注意不能直接在run()方法前加synchronized因为这样会使得只有一个窗口可以进入卖票使得其他窗口一直处于锁死状态直至票卖完退出。
public class SellTicket {public static void main(String[] args) {SellTicketByRunnable sellTicketByRunnable new SellTicketByRunnable();new Thread(sellTicketByRunnable).start();//第1个线程-窗口new Thread(sellTicketByRunnable).start();//第2个线程-窗口new Thread(sellTicketByRunnable).start();//第3个线程-窗口}
}class SellTicketByRunnable implements Runnable {//让多个线程共享TICKET_NUMBERprivate static int TICKET_NUMBER 100;private Boolean loop true;public synchronized void sell() {if (TICKET_NUMBER 0) {System.out.println(售票结束);loopfalse;return;}try {Thread.sleep(50);} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println(窗口 Thread.currentThread().getName() 售出一张票剩余票数 (--TICKET_NUMBER));}Overridepublic void run() {while (loop) {sell();}}
}六、互斥锁
6.1 基本介绍
Java语言中引入了对象互斥锁的概念来保证共享数据的完整性。每个对象都对应于一个可称为“互斥锁”的标记这个标记用来保证在任意时刻只能有一个线程访问该对象。关键字synchronized来与对象的互斥锁联系当某个对象用synchronized修饰时表明该对象在任一时刻只能由一个线程访问。同步的局限性导致程序的执行效率要降低。同步方法非静态的的锁可以是this也可以是其他对象要求是同一个对象。同步方法静态的的锁为当前类本身。
代码示例-实现接口的同步
方法一在方法上添加synchronized修饰默认锁在this对象 方法二在方法内部设置同步代码块添加修饰锁可以在this对象或者自己创建的Object对象也可以在其他对象但是必须是同一个对象若不是同一个对象那么不同线程操作的对象就不同了就不存在同步问题了。 方法三在静态方法内设置synchronized修饰的同步代码块默认锁在该类 方法四在静态方法上添加synchronized修饰默认锁在该类 代码示例-继承类的同步
方法一静态方法直接写synchronized修饰默认锁在该类 方法二静态方法内部写同步代码块默认的锁在该类 6.2 注意事项和细节
同步方法如果没有使用static修饰默认锁对象为this如果方法使用static修饰默认锁对象为 当前类名.class实现的步骤 需要先分析上锁的代码选择同步代码块范围小效率高优先选择或者同步方法要求多个线程的锁对象为同一个
七、死锁
多个线程都占用了对方的资源都不肯相让导致了死锁在编程中一定要避免死锁的发生。
public class DeadLock_ {public static void main(String[] args) {//模拟死锁现象DeadLockDemo A new DeadLockDemo(true);A.setName(A线程);DeadLockDemo B new DeadLockDemo(false);B.setName(B线程);A.start();B.start();}
}//线程
class DeadLockDemo extends Thread {static Object o1 new Object();// 保证多线程共享一个对象,这里使用staticstatic Object o2 new Object();boolean flag;public DeadLockDemo(boolean flag) {//构造器this.flag flag;}Overridepublic void run() {//下面业务逻辑的分析//1. 如果flag 为 T, 线程A 就会先得到/持有 o1 对象锁, 然后尝试去获取 o2 对象锁//2. 如果线程A 得不到 o2 对象锁就会Blocked//3. 如果flag 为 F, 线程B 就会先得到/持有 o2 对象锁, 然后尝试去获取 o1 对象锁//4. 如果线程B 得不到 o1 对象锁就会Blockedif (flag) {synchronized (o1) {//对象互斥锁, 下面就是同步代码System.out.println(Thread.currentThread().getName() 进入1);synchronized (o2) { // 这里获得li对象的监视权System.out.println(Thread.currentThread().getName() 进入2);}}} else {synchronized (o2) {System.out.println(Thread.currentThread().getName() 进入3);synchronized (o1) { // 这里获得li对象的监视权System.out.println(Thread.currentThread().getName() 进入4);}}}}
}八、释放锁
下面操作会释放锁
当前线程的同步方法、同步代码块执行结束。当前线程在同步代码块、同步方法中遇到break、return。当前线程在同步代码块、同步方法中出现了未处理的Error或Exception导致异常结束。当前线程在同步代码块、同步方法中执行了线程对象的wait()方法当前线程停止并释放锁。
下面操作不会释放锁 线程执行同步代码块或同步方法时程序调用Thread.sleep()Thread.yield()方法暂停当前线程的执行不会释放锁。 线程执行同步代码块时其他线程调用了该线程的suspend()方法将该线程挂起该线程不会释放锁。 提示不推荐使用suspend()和resume()来控制线程。
九、练习
练习二 public class Homework01 {public static void main(String[] args) {A a new A();B b new B(a);//一定要注意.a.start();b.start();}
}//创建A线程类
class A extends Thread {private boolean loop true;Overridepublic void run() {//输出1-100数字while (loop) {System.out.println((int)(Math.random() * 100 1));//休眠try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}System.out.println(a线程退出...);}public void setLoop(boolean loop) {//可以修改loop变量this.loop loop;}
}//直到第2个线程从键盘读取了“Q”命令
class B extends Thread {private A a;private Scanner scanner new Scanner(System.in);public B(A a) {//构造器中直接传入A类对象this.a a;}Overridepublic void run() {while (true) {//接收到用户的输入System.out.println(请输入你指令(Q)表示退出:);char key scanner.next().toUpperCase().charAt(0);if(key Q) {//以通知的方式结束a线程a.setLoop(false);System.out.println(b线程退出.);break;}}}
}练习二 public class Homework02 {public static void main(String[] args) {T t new T();Thread thread1 new Thread(t);thread1.setName(t1);Thread thread2 new Thread(t);thread2.setName(t2);thread1.start();thread2.start();}
}//编程取款的线程
//1.因为这里涉及到多个线程共享资源所以我们使用实现Runnable方式
//2. 每次取出 1000
class T implements Runnable {private int money 10000;Overridepublic void run() {while (true) {//解读//1. 这里使用 synchronized 实现了线程同步//2. 当多个线程执行到这里时就会去争夺 this对象锁//3. 哪个线程争夺到(获取)this对象锁就执行 synchronized 代码块, 执行完后会释放this对象锁//4. 争夺不到this对象锁就blocked 准备继续争夺//5. this对象锁是非公平锁.synchronized (this) {////判断余额是否够if (money 1000) {System.out.println(余额不足);break;}money - 1000;System.out.println(Thread.currentThread().getName() 取出了1000 当前余额 money);}//休眠1stry {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}
}