本文内容来源于  历经5年锤练--史上最适合初学者入门的Java基础视频

线程:就是进程中一个负责程序执行的控制单元(执行路径)

每一个线程都有自己运行的内容。这个内容可以称为线程要执行的任务。

多线程好处:解决了多部分同时运行的问题。

多线程的弊端:线程太多回到效率的降低。

JVM启动时就启动了多个线程,至少有两个线程可以分析的出来。

1,执行main函数的线程,
该线程的任务代码都定义在main函数中。

2,负责垃圾回收的线程。

多线程状态图:

如何创建一个线程呢?

创建线程方式一:继承Thread类。

步骤:
1,定义一个类继承Thread类。
2,覆盖Thread类中的run方法。
3,直接创建Thread的子类对象创建线程。
4,调用start方法开启线程并调用线程的任务run方法执行。

  1. class Demo extends Thread{
  2.   ......
  3.   public void run(){
  4.     ......
  5.   }
  6. }
  7. class ThreadDemo2 {
  8.   public static void main(String[] args) {
  9.      Demo d1 = new Demo();
  10.     d1.start();//开启线程,调用run方法。
  11. }
  1. class Demo extends Thread{
  2.   private String name;
  3.   Demo(String name){
  4.     super(name);
  5.     //this.name = name;
  6.   }
  7.   public void run(){
  8.     for(int x=0; x<10; x++){
  9.       System.out.println(name+"....x="+x+".....name="+Thread.currentThread().getName());
  10.     }
  11.   }
  12. }
  13.  
  14. class ThreadDemo2 {
  15.   public static void main(String[] args) {
  16.      Demo d1 = new Demo("旺财");
  17.     Demo d2 = new Demo("xiaoqiang");
  18.     d1.start();//开启线程,调用run方法。
  19.     d2.start();
  20.     System.out.println("over...."+Thread.currentThread().getName());
  21.   }
  22. }

线程创建方式二:实现Runnable接口(比较常用)

步骤:
1,定义类实现Runnable接口。
2,覆盖接口中的run方法,将线程的任务代码封装到run方法中。
3,通过Thread类创建线程对象,并将Runnable接口的子类对象作为Thread类的构造函数的参数进行传递。
4,调用线程对象的start方法开启线程。

实现Runnable接口的好处:
1,将线程的任务从线程的子类中分离出来,进行了单独的封装。
按照面向对象的思想将任务的封装成对象。
2,避免了java单继承的局限性。

  1. class Demo implements Runnable{
  2. public void run(){
  3. ...
  4. }
  5. }
  6. class ThreadDemo{
  7. public static void main(String[] args) {
  8. Demo d = new Demo();
  9. Thread t1 = new Thread(d);
  10. Thread t2 = new Thread(d);
  11. t1.start();
  12. t2.start();
  13. }
  14. }

小例子:卖票

线程安全问题产生的原因:

1,多个线程在操作共享的数据。
2,操作共享数据的线程代码有多条。

当一个线程在执行操作共享数据的多条代码过程中,其他线程参与了运算。
就会导致线程安全问题的产生。

解决思路;
就是将多条操作共享数据的线程代码封装起来,当有线程在执行这些代码的时候,
其他线程时不可以参与运算的,必须要当前线程把这些代码都执行完毕后,其他线程才可以参与运算。

在java中,用同步代码块就可以解决这个问题。

同步代码块的格式:
synchronized(对象)
{
  需要被同步的代码 ;
}

同步的好处:解决了线程的安全问题。

同步的弊端:相对降低了效率,因为同步外的线程的都会判断同步锁。

同步的前提:同步中必须有多个线程并使用同一个锁。

  1. class Ticket implements Runnable{
  2. private int num = 100;
  3.  
  4. Object obj = new Object();
  5. public void run(){
  6. while(true){
  7. synchronized(obj){  //锁是任意的,可以使用this,即 synchronized(this)
  8. if(num>0){
  9. try{Thread.sleep(10);}catch (InterruptedException e){} //睡一下便于发现是否有安全隐患
                System.out.println(Thread.currentThread().getName()+".....sale...."+num--);
  10. }
  11. }
  12. }
  13. }
  14. }
  15. class TicketDemo{
  16. public static void main(String[] args) {
  17.  
  18. Ticket t = new Ticket();//创建一个线程任务对象。
  19.  
  20. Thread t1 = new Thread(t);
  21. Thread t2 = new Thread(t);
  22. Thread t3 = new Thread(t);
  23. Thread t4 = new Thread(t);
  24.  
  25. t1.start();
  26. t2.start();
  27. t3.start();
  28. t4.start();
  29. }
  30. }

小例子2:储户,两个,每个都到银行(同一个银行)存钱每次存100,,共存三次。

 涉及:同步函数

  1. class Bank{
  2. private int sum;
  3. public synchronized void add(int num)//同步函数:同步的第二种表现形式,锁是this
  4. {
  5. sum = sum + num;
  6. try{Thread.sleep(10);}catch(InterruptedException e){}
  7. System.out.println("sum="+sum);
  8. }
  9. }
  10. class Cus implements Runnable{
  11. private Bank b = new Bank();
  12. public void run(){
  13. for(int x=0; x<3; x++){
  14. b.add(100);
  15. }
  16. }
  17. }
  18. class BankDemo {
  19. public static void main(String[] args) {
  20. Cus c = new Cus();
  21. Thread t1 = new Thread(c);
  22. Thread t2 = new Thread(c);
  23. t1.start();
  24. t2.start();
  25. }
  26. }

同步函数锁:

同步函数的使用的锁是this;

同步函数和同步代码块的区别:同步函数的锁是固定的this, 同步代码块的锁是任意的对象。

建议使用同步代码块。

静态的同步函数使用的锁是 该函数所属字节码文件对象
可以用 getClass方法获取,也可以用当前 类名.class 表示。

  1. class Ticket implements Runnable{
  2. private static int num = 100;
  3. // Object obj = new Object();
  4. boolean flag = true;
  5. public void run(){
  6. // System.out.println("this:"+this.getClass());
  7. if(flag)
  8. while(true){
  9.       synchronized(Ticket.class)//(this.getClass())
  10. {  if(num>0){
  11. try{Thread.sleep(10);}catch (InterruptedException e){}
  12. System.out.println(Thread.currentThread().getName()+".....obj...."+num--);
  13. }
  14. }
  15. }
  16. else
  17. while(true)
  18. this.show();
  19. }
  20. public static synchronized void show(){
  21. if(num>0){
  22. try{Thread.sleep(10);}catch (InterruptedException e){}
  23. System.out.println(Thread.currentThread().getName()+".....function...."+num--);
  24. }
  25. }
  26. }
  27. class StaticSynFunctionLockDemo {
  28. public static void main(String[] args) {
  29. Ticket t = new Ticket();
  30. // Class clazz = t.getClass();
  31. // Class clazz = Ticket.class;
  32. // System.out.println("t:"+t.getClass());
  33.  
  34. Thread t1 = new Thread(t);
  35. Thread t2 = new Thread(t);
  36.  
  37. t1.start();
  38. try{Thread.sleep(10);}catch(InterruptedException e){}
  39. t.flag = false;
  40. t2.start();
  41. }
  42. }

复习:单例设计模式 

设计模式:对问题行之有效的解决方式。其实它是一种思想。

1,单例设计模式。
解决的问题:就是可以保证一个类在内存中的对象唯一性。

必须对于多个程序使用同一个配置信息对象时,就需要保证该对象的唯一性。

如何保证对象唯一性呢?
1,不允许其他程序用new创建该类对象。
2,在该类创建一个本类实例。
3,对外提供一个方法让其他程序可以获取该对象。

步骤:
1,私有化该类构造函数。
2,通过new在本类中创建一个本类对象。
3,定义一个公有的方法,将创建的对象返回。

//饿汉式(开发常用)

  1. class Single//类一加载,对象就已经存在了。
  2. {
  3.   private static Single s = new Single();
  4.   private Single(){}
  5.   public static Single getInstance()
  6.   {return s;}
  7. }

//懒汉式(面试常用)有安全问题

  1. class Single2//类加载进来,没有对象,只有调用了getInstance方法时,才会创建对象。延迟加载形式。
  2. { private static Single2 s = null;
  3.   private Single2(){}
  4.   public static Single2 getInstance(){
        if(s==null)
  5.     s = new Single2();
  6.     return s;}
  7. }

多线程下的单例模式:

饿汉式没有安全问题,对懒汉式进行修改

加入同步为了解决多线程安全问题。

加入双重判断是为了解决效率问题。

  1. class Single{
  2.   private static Single s = null;
  3.   private Single(){}
  4.   public static Single getInstance(){
  5.     if(s==null){//当s不为null时,则不进行锁的判断,直接返回s
  6.       synchronized(Single.class){
  7.         if(s==null)
  8.         // -->0 -->1
  9.         s = new Single();
  10.       }
  11.     }
  12.   return s;
  13.   }
  14. }

死锁: 常见情景之一:同步的嵌套。

  1. class Ticket implements Runnable{
  2. private int num = 100;
  3. Object obj = new Object();
  4. boolean flag = true;
  5. public void run(){
  6. if(flag)
  7. while(true){
  8. synchronized(obj){
  9. show();
  10. }
  11. }
  12. else
  13. while(true)
  14. this.show();
  15. }
  16. public synchronized void show(){
  17. synchronized(obj){
  18. if(num>0){
  19. try{Thread.sleep(10);}catch (InterruptedException e){} System.out.println(Thread.currentThread().getName()+".....sale...."+num--);
  20. }
  21. }
  22. }
  23. }
  24. class DeadLockDemo {
  25. public static void main(String[] args) {
  26. Ticket t = new Ticket();
  27. // System.out.println("t:"+t);
  28.  
  29. Thread t1 = new Thread(t);
  30. Thread t2 = new Thread(t);
  31.  
  32. t1.start();
  33. try{Thread.sleep(10);}catch(InterruptedException e){}
  34. t.flag = false;
  35. t2.start();
  36. }
  37. }

死锁同步嵌套Demo

  1. class Test implements Runnable
  2. {
  3. private boolean flag;
  4. Test(boolean flag){
  5. this.flag = flag;
  6. }
  7. public void run(){
  8. if(flag){
  9. while(true)
  10. synchronized(MyLock.locka){
  11. System.out.println(Thread.currentThread().getName()+"..if locka....");
  12. synchronized(MyLock.lockb) {
  13. System.out.println(Thread.currentThread().getName()+"..if lockb....");
  14. }
  15. }
  16. }
  17. else{
  18. while(true)
  19. synchronized(MyLock.lockb){
  20. System.out.println(Thread.currentThread().getName()+"..else lockb....");
  21. synchronized(MyLock.locka){
  22. System.out.println(Thread.currentThread().getName()+"..else locka....");
  23. }
  24. }
  25. }
  26. }
  27. }
  28. class MyLock{
  29. public static final Object locka = new Object();
  30. public static final Object lockb = new Object();
  31. }
  32. class DeadLockTest {
  33. public static void main(String[] args) {
  34. Test a = new Test(true);
  35. Test b = new Test(false);
  36.  
  37. Thread t1 = new Thread(a);
  38. Thread t2 = new Thread(b);
  39. t1.start();
  40. t2.start();
  41. }
  42. }

线程间通讯:
多个线程在处理同一资源,但是任务却不同。

  1. //资源
  2. class Resource{
  3. String name;
  4. String sex;
  5. }
  6. //输入
  7. class Input implements Runnable{
  8. Resource r ;
  9. // Object obj = new Object();
  10. Input(Resource r){
  11. this.r = r;
  12. }
  13. public void run(){
  14. int x = 0;
  15. while(true){
  16. synchronized(r){
  17. if(x==0){
  18. r.name = "mike";
  19. r.sex = "nan";
  20. }
  21. else{
  22. r.name = "丽丽";
  23. r.sex = "女女女女女女";
  24. }
  25. }
  26. x = (x+1)%2;
  27. }
  28. }
  29. }
  30. //输出
  31. class Output implements Runnable{
  32. Resource r;
  33. // Object obj = new Object();
  34. Output(Resource r){
  35. this.r = r;
  36. }
  37. public void run(){
  38. while(true){
  39. synchronized(r){
  40. System.out.println(r.name+"....."+r.sex);
  41. }
  42. }
  43. }
  44. }
  45. class ResourceDemo{
  46. public static void main(String[] args) {
  47. //创建资源。
  48. Resource r = new Resource();
  49. //创建任务。
  50. Input in = new Input(r);
  51. Output out = new Output(r);
  52. //创建线程,执行路径。
  53. Thread t1 = new Thread(in);
  54. Thread t2 = new Thread(out);
  55. //开启线程
  56. t1.start();
  57. t2.start();
  58. }
  59. }

线程间通讯:等待唤醒机制

等待/唤醒机制。

涉及的方法:

1,wait(): 让线程处于冻结状态,被wait的线程会被存储到线程池中。
2,notify():唤醒线程池中一个线程(任意).
3,notifyAll():唤醒线程池中的所有线程。

这些方法都必须定义在同步中。
因为这些方法是用于操作线程状态的方法。
必须要明确到底操作的是哪个锁上的线程。

为什么操作线程的方法wait notify notifyAll定义在了Object类中?

因为这些方法是监视器的方法。监视器其实就是锁。
锁可以是任意的对象,任意的对象调用的方式一定定义在Object类中。

  1. //资源
  2. class Resource
  3. {
  4. String name;
  5. String sex;
  6. boolean flag = false;
  7. }
  8. //输入
  9. class Input implements Runnable
  10. {
  11. Resource r ;
  12. // Object obj = new Object();
  13. Input(Resource r)
  14. {
  15. this.r = r;
  16. }
  17. public void run()
  18. {
  19. int x = 0;
  20. while(true)
  21. {
  22. synchronized(r)
  23. {
  24. if(r.flag)
  25. try{r.wait();}catch(InterruptedException e){}
  26. if(x==0)
  27. {
  28. r.name = "mike";
  29. r.sex = "nan";
  30. }
  31. else
  32. {
  33. r.name = "丽丽";
  34. r.sex = "女女女女女女";
  35. }
  36. r.flag = true;
  37. r.notify();
  38. }
  39. x = (x+1)%2;
  40.  
  41. }
  42. }
  43. }
  44. //输出
  45. class Output implements Runnable
  46. {
  47.  
  48. Resource r;
  49. // Object obj = new Object();
  50. Output(Resource r)
  51. {
  52. this.r = r;
  53. }
  54.  
  55. public void run()
  56. {
  57. while(true)
  58. {
  59. synchronized(r)
  60. {
  61. if(!r.flag)
  62. try{r.wait();}catch(InterruptedException e){}
  63. System.out.println(r.name+"....."+r.sex);
  64. r.flag = false;
  65. r.notify();
  66. }
  67. }
  68. }
  69. }
  70. class ResourceDemo2
  71. {
  72. public static void main(String[] args)
  73. {
  74. //创建资源。
  75. Resource r = new Resource();
  76. //创建任务。
  77. Input in = new Input(r);
  78. Output out = new Output(r);
  79. //创建线程,执行路径。
  80. Thread t1 = new Thread(in);
  81. Thread t2 = new Thread(out);
  82. //开启线程
  83. t1.start();
  84. t2.start();
  85. }
  86. }

代码优化:

  1. class Resource
  2. {
  3. private String name;
  4. private String sex;
  5. private boolean flag = false;
  6. public synchronized void set(String name,String sex)
  7. {
  8. if(flag)
  9. try{this.wait();}catch(InterruptedException e){}
  10. this.name = name;
  11. this.sex = sex;
  12. flag = true;
  13. this.notify();
  14. }
  15. public synchronized void out()
  16. {
  17. if(!flag)
  18. try{this.wait();}catch(InterruptedException e){}
  19. System.out.println(name+"...+...."+sex);
  20. flag = false;
  21. notify();
  22. }
  23. }
  24. //输入
  25. class Input implements Runnable
  26. {
  27. Resource r ;
  28. // Object obj = new Object();
  29. Input(Resource r)
  30. {
  31. this.r = r;
  32. }
  33. public void run()
  34. {
  35. int x = 0;
  36. while(true)
  37. {
  38. if(x==0)
  39. {
  40. r.set("mike","nan");
  41. }
  42. else
  43. {
  44. r.set("丽丽","女女女女女女");
  45. }
  46. x = (x+1)%2;
  47. }
  48. }
  49. }
  50. //输出
  51. class Output implements Runnable
  52. {
  53. Resource r;
  54. // Object obj = new Object();
  55. Output(Resource r)
  56. {
  57. this.r = r;
  58. }
  59. public void run()
  60. {
  61. while(true)
  62. {
  63. r.out();
  64. }
  65. }
  66. }
  67. class ResourceDemo3
  68. {
  69. public static void main(String[] args)
  70. {
  71. //创建资源。
  72. Resource r = new Resource();
  73. //创建任务。
  74. Input in = new Input(r);
  75. Output out = new Output(r);
  76. //创建线程,执行路径。
  77. Thread t1 = new Thread(in);
  78. Thread t2 = new Thread(out);
  79. //开启线程
  80. t1.start();
  81. t2.start();
  82. }
  83. }

未完......

java学习——多线程的更多相关文章

  1. Java学习多线程第一天

    内容介绍 Thread 线程创建 线程池 线程状态图 1 多线程 1.1     多线程介绍 学习多线程之前,我们先要了解几个关于多线程有关的概念. 进程:进程指正在运行的程序.确切的来说,当一个程序 ...

  2. Java学习---多线程的学习

    基础知识 每个正在系统上运行的程序都是一个进程(process).每个进程包含一到多个线程(thread).进程也可能是整个程序或者是部分程序的动态执行. 线程是一组指令的集合,或者是程序的特殊段,它 ...

  3. java学习多线程之生产者消费者

    在java多线程当中还有一种关系需要我们来重点掌握,那就是生产者和消费者的关系.那么什么是生产者,什么是消费者呢?我们可以举个例子来说,有张三.李四负责生产烤鸭,王五.马六负责吃烤鸭,那么前者生产完烤 ...

  4. java学习多线程之卖票示例

    这一节我们来说一个示例就是卖票示例: 需求: 我们现在有100张票,然后分四个窗口来卖,直到卖完为止. 思路: 1.先定一个一个票类,描述票的属性,还有打印卖出的票,并且实现Runnable中的run ...

  5. java学习多线程之创建多线程一

    现在我们有这么一个需求,就是在主线程在运行的同时,我们想做其他的任务,这个时候我们就用到了多线程.那么如何创建多线程,我们知道在系统当中qq的多线程创建是由操作系统来完成的,那么如果我们想在java当 ...

  6. [Java学习]多线程

    关于多进程与多线程 使用多进程的目的:提高CPU利用率. 使用多线程的目的:提高应用程序?利用率. 多线程与多进程区别:进程间内存独立:同一个进程的线程间共享"堆内存和方法区内存" ...

  7. Java学习多线程第二天

    内容介绍 线程安全 线程同步 死锁 Lock锁 等待唤醒机制 1    多线程 1.1     线程安全 如果有多个线程在同时运行,而这些线程可能会同时运行这段代码.程序每次运行结果和单线程运行的结果 ...

  8. Java学习|多线程学习笔记

    什么是线程?     可以理解为进程中独立运行的字任务.   使用多线程:     1.继承Thread类:从源码可以看到,Thread累实现了Runnable接口.         如果多次调用st ...

  9. java学习多线程之死锁

    形成死锁的前提是同步代码块嵌套. 什么是死锁?当一个线程拿到锁以后在这个锁内部的代码需要访问另一段的代码的时候另外一个程序的锁被另外一个线程拿到,这样的话,就造成了两个锁互不想让程序没法往下执行的这种 ...

随机推荐

  1. Android 判断当前网络连接类型

    实际应用开发时,如果存在需要用户获取大量数据的情况,最好是先判断下网络类型,提示用户当前的网络类型,是否需要连接Wifi,etc.(手机流量太贵啦,当然土豪是无视这玩意的, (/ □ \)). 定义网 ...

  2. Acunetix Web Vulnerability Scanner Python辅助脚本

    WvsScannerQueue.pyVersion: Python 2.7.* Acunetix Web Vulnerability Scanner 辅助Python脚本的第一个版本.功能:扫描URL ...

  3. SPSS时间序列分析

    时间序列分析必须建立在预处理的基础上…… 今天看了一条新闻体会到了网络日志的重要性…… 指数平滑法(Exponential Smoothing,ES)是布朗(Robert G..Brown)所提出,布 ...

  4. osvdb

    http://www.91ri.org/3117.html http://linux.cn/article-5332-1-rss.html http://www.freebuf.com/article ...

  5. UMHexagonS搜索过程

    通过相邻块的预测得到mvp后,会以mvp为基础搜索最佳的匹配块,UMHexagonS就是h.264中用的一种搜索算法. UMHexagonS是一种整像素搜索算法,也就是搜索过程中,参考图像一直都是原来 ...

  6. Windows NT 驱动程序开发人员提示 -- 应注意避免的事项

    下面是开发人员在使用 Windows NT 设备驱动程序时应当避免的事项列表: 1.  一定不要在没有标注 I/O 请求数据包 (IRP) 挂起 (IoMarkIrpPending) 的情况下通过调度 ...

  7. 设计模式(六):Singleton 单件模式 -- 创建型模式

    1.定义 当需要控制一个类的实例数量且调用者可以从一个公共的访问点访问时. 2.适用场景 1. 当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时. 2. 当这个唯一实例应该是通过子类化可扩 ...

  8. 前端问题——png图片在IE6下透明失效,解决办法

    今天,一位同事问我问题,png 图片在IE6下透明背景失效. 解决办法,在网上查了很多,最后还是采用两种方案来解决这个问题 1.把这个网页的png格式图片变更为gif格式的图片.问题解决 2.就是让这 ...

  9. UVAlive4287 Proving Equivalences(scc)

    题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=10294 [思路] 强连通分量. 求出bcc后,缩点形成DAG,设D ...

  10. [git] github 使用简单记录

    前提 :1. 已有 github 账号.2. 已安装 git .3. 在 github 和 本地 git 客户端交互秘钥.(这步我记得需要做,有点久远,不确定.) 正文: 下面是一个简单的例子.先在 ...