zoukankan      html  css  js  c++  java
  • 多线程

    
    

    多线程

    
    
    1.概念
        同一进程内并发执行的代码块。
        灵活响应的桌面程序。
        界面友好,用户体验。
        耗时应用.
    2.
    3.
    4.
    
    并发计算        //通常指同一进程内的多个线程并发执行。
    并行计算        //硬件资源层面,集群计算。
    

    Thread

    java.lang.Thread
    class MyThread
    
    1.不要较真.
    2.start();
    
    Thread.start()              //开启线程
    Thread.run()                //线程执行方法。
    static Thread.yield()       //放弃CPU抢占权,瞬间即逝。谦让的意思。
    
    static Thread.sleep()       //让当前线程休眠时间(毫秒)
    Thread.join()               //等待分线程执行完成后再运行。
    
    Daemon                      //守护线程,以服务的身份出现。
                                //守护线程守护的非守护线程,如果进程内剩余的线程都是守护线程,应用就结束了。
    

    安全问题

    买票问题。
    

    Debug

    锁.
    blocked         //阻塞
    synchronized    //同步,使用的同一把锁.
                    //synchronized(obj){...}
                    //同步方法粒度较粗。非静态方法以当前对象为锁。
                    //静态方法以class为锁。
    
    粒度          //粒度粗细.
    

    汽车过山洞

    
    
    1. 5辆汽车,
    2. 每次通过一辆汽车。
    3. 每辆汽车通过时间不同(1m 2m 3m 4m 5m)。
    4. 通过多线程模拟.
    
    [stack]
    FILO        //first in last out
    
    [queue]
    FIFO        //fist in first out
    

    堆区

    栈区

    默认1m空间。
    11xxx多方法后溢出。
    
    2m:
    23xxx方法后溢出。
    
    package com.it18zhang.thread.stack;
    
    public class StackOverflowDemo {
        public static void main(String[] args) {
            sayHello(1);
        }
    
        public static void sayHello(int i){
            System.out.println(i);
            i ++ ;
            sayHello(i);
        }
    }
    //
    method
    
    java            //java命令行帮助
    java -X         //查看非标准选项
    
    java -X
    
    java -Xss2m     //java stackSize,默认1m. 11xxx
    

    这是jvm堆空间大小

    
    
    java -Xmx20m    //最大值
    java -Xms20m    //初始值
    

    OutOfMemoryError

    内存溢出.堆空间不足。
    
    notyfyAll   //获得锁旗标后才能调
    sleep()     //
    wait();     //获得锁旗标后才能调



    1
    /**

    2 蜜蜂和熊的生产消费关系,熊能在蜜蜂10斤吃掉,蜜蜂一次生产一斤蜂蜜,且蜜蜂生产一斤蜂蜜话费的时间 3 是10ms 4 蜜蜂:有个包,最大容量Max=20斤,每次产1斤,耗时10ms; 满足5斤的时候给蜜罐添加 5 蜜罐:最大容量max=30; 6 2只熊 7 8 */ 9 public class BeeDemo{ 10 public static void main(String[]args){ 11 Box box=new Box();//蜜罐 12 Bee bee1=new Bee("b-1",box); 13 Bee bee2=new Bee("b-2",box); 14 Bee bee3=new Bee("b-3",box); 15 Bee bee4=new Bee("b-4",box); 16 Bee bee5=new Bee("b-5",box); 17 Bee bee6=new Bee("b-6",box); 18 Bee bee7=new Bee("b-7",box); 19 Bee bee8=new Bee("b-8",box); 20 Bee bee9=new Bee("b-9",box); 21 Bee bee10=new Bee("b-10",box); 22 Bear bear1=new Bear(box,"熊大"); 23 // Bear bear2=new Bear(box,"熊二"); 24 bee1.start(); 25 bee2.start(); 26 bee3.start(); 27 bee4.start(); 28 bee5.start(); 29 bee6.start(); 30 bee7.start(); 31 bee8.start(); 32 bee9.start(); 33 bee10.start(); 34 bear1.start(); 35 // bear2.start(); 36 } 37 } 38 //蜜蜂 39 class Bee extends Thread{ 40 private int bag; 41 private static final int BAG_MAX=20;//包的最大容量 42 private static final int ONCE=5;//没生产5斤可以放入蜜罐 43 private static final int TIME=10;//生产一斤话费10ms 44 private Box box; 45 private String name; 46 public Bee(String name,Box box){ 47 this.name=name; 48 this.box=box; 49 } 50 public void run(){ 51 while(true){ 52 //满足放蜂蜜条件 53 if(bag>=5){ 54 synchronized(box){ 55 //当前蜜罐的量 56 int cap=box.capacity; 57 //蜜罐已满 58 if(cap>=box.MAX){ 59 box.notifyAll();//通知熊来吃 60 } 61 //蜜罐未满 62 else{ 63 //蜜罐剩余空间 64 int remain=box.MAX-cap; 65 //蜂蜜带的蜂蜜可以装满蜜罐 66 if(bag>=remain){ 67 box.capacity=Box.MAX; 68 //放后蜜蜂的小包剩余量 69 bag=bag-remain; 70 System.out.println(name+",添加了="+remain+",name.bag="+bag+",蜜罐有"+box.capacity); 71 72 box.notifyAll();//通知熊来吃 73 } 74 //蜜蜂的小包量不足以加满蜜罐 75 else{ 76 box.capacity=box.capacity+bag; 77 System.out.println(name+",添加了="+bag+",name.bag=:"+bag+",蜜罐有"+box.capacity); 78 bag=0; 79 } 80 } 81 } 82 83 } 84 //向小包增加蜂蜜 85 if(bag>=Bee.BAG_MAX){ 86 synchronized(box){ 87 try{ 88 box.wait(); 89 }catch(Exception e){ 90 } 91 } 92 } 93 else{ 94 bag++; 95 System.out.println(name+".bag:"+bag); 96 try{ 97 Thread.sleep(10);//休眠10ms 98 }catch(Exception e){ 99 } 100 } 101 } 102 } 103 } 104 //蜜罐 105 class Box{ 106 public static final int MAX=30;//蜜罐最大容量 107 public int capacity=0;//目前蜂蜜的的量,初始为0 108 } 109 // 110 class Bear extends Thread{ 111 private Box box; 112 private String name; 113 public Bear(Box box,String name){ 114 super(); 115 this.box=box; 116 this.name=name; 117 } 118 public void run(){ 119 while(true){ 120 121 synchronized(box){ 122 if(box.capacity==Box.MAX){ 123 System.out.println(name+":吃掉了"+box.capacity); 124 box.capacity=0; 125 try{ 126 Thread.sleep(1000); 127 }catch(Exception e){ 128 129 } 130 box.notifyAll(); 131 } 132 else{ 133 try{ 134 135 box.wait(); 136 }catch(Exception e){ 137 e.printStackTrace(); 138 } 139 } 140 } 141 } 142 143 } 144 }

    2、

      1 /**
      2  * 100个和尚。
      3     300馒头
      4     每个和尚最多吃4个馒头。
      5     每个和尚至少吃一个馒头.
      6     尽可能快的把馒头吃掉。
      7  *
      8  */
      9 public class MonkMain {
     10 
     11     public static void main(String[] args) {
     12         Basket bas = new Basket();
     13         for(int i=1;i<=100;i++){
     14             new Monk("和尚"+i,bas).start();
     15         }
     16     }
     17 }
     18 
     19 
     20 public class Basket {
     21     private String name;
     22     private Monk monk;
     23     private static int MANTOU_COUNT = 300;// 馒头总数
     24     private int MONKS_COUNT = 100;// 和尚总数
     25     private int remainManos = MANTOU_COUNT;// 剩余馒头数
     26     private int remainMonks = MONKS_COUNT;// 剩余没吃馒头的和尚
     27 
     28     // 和尚取馒头
     29     public synchronized int getMantou(Monk monk) {
     30         // 如果剩余馒头为0
     31         if (remainManos == 0) {
     32             return 0;
     33         }
     34         // 如果和尚已经吃了4个,则不能再取馒头
     35         if (monk.getEatList().size() >= monk.MAX) {
     36             return 0;
     37         }
     38         // 剩余馒头数大于一次还没取馒头的和尚数
     39         if (remainManos > remainMonks) {
     40             // 当前和尚还没吃过馒头
     41             if (monk.getEatList().size() == 0) {
     42                 // 可以继续取馒头,馒头剩余数减少1
     43                 int tem = remainManos;
     44                 remainManos--;
     45                 // 剩余没吃馒头的和尚数减少1
     46                 remainMonks--;
     47                 return tem;
     48             } else {// 当前和尚吃过馒头
     49                     // 直接剩余馒头数减去1
     50                 int tem = remainManos;
     51                 remainManos--;
     52                 return tem;
     53             }
     54         }
     55         // 剩余馒头数=一次还没取馒头的和尚数
     56         if (remainManos == remainMonks) {
     57             // 当前取馒头的是还没吃过的和尚,可以取走
     58             if (monk.getEatList().size() == 0) {
     59                 int tem = remainManos;
     60                 remainManos--;
     61                 remainMonks--;
     62                 return tem;
     63             } else {// 当前取馒头的和尚已经吃过了,则不能再吃了
     64                 return 0;
     65             }
     66         } else {
     67             return 0;
     68         }
     69     }
     70 }
     71 
     72 public class Monk extends Thread {
     73     private String name;
     74     private Basket bas;
     75     public static int MAX=4;//做多吃的馒头数
     76     
     77     ArrayList<Integer> eatList =new ArrayList();//吃的馒头容器
     78     public Monk(String name, Basket bas) {
     79         super();
     80         this.name = name;
     81         this.bas = bas;
     82     }
     83     public ArrayList getEatList() {
     84         return eatList;
     85     }
     86     @Override
     87     public void run() {
     88         while(true){
     89             int mantoNo=bas.getMantou(this);//当前吃的馒头编号
     90             if(mantoNo!=0){
     91                 eatList.add(mantoNo);
     92             }        
     93             else{
     94                 break;
     95             }
     96         }    
     97         String str="";
     98         for (Integer i : eatList) {
     99             str=str+i+",";
    100         }
    101         System.out.println(name+"总共吃了"+eatList.size()+"个馒头,编号分别为:"+str);
    102     }
    103 }

    3、

     1 class Syn{
     2     public static void main(String[]args){
     3         Pool pool=new Pool();
     4     Produce p1=new Produce("王二",pool);
     5     Produce p2=new Produce("赵四",pool);
     6     Produce p3=new Produce("麻子",pool);
     7     Consumer c1=new Consumer("lisi",pool);
     8     Consumer c2=new Consumer("Tom",pool);
     9         p1.start();
    10         p2.start();
    11         p3.start();
    12         c1.start();
    13         c2.start();
    14     }
    15 }
    16 //生产者
    17 class Produce extends Thread{
    18     private String name;
    19     private Pool pool;
    20     public Produce(){};
    21     public Produce(String name,Pool pool){
    22         this.name=name;
    23         this.pool=pool;
    24     }
    25     public void run(){
    26         int i=0;
    27         pool.add(i++);
    28         try{
    29             
    30         Thread.sleep(100);
    31         }catch(Exception e){}
    32         System.out.println("生产:"+i);
    33     }
    34 }
    35 //消费者
    36 class Consumer extends Thread{
    37     private String name;
    38     private Pool pool;
    39     public Consumer(){}
    40     public Consumer(String name,Pool pool){
    41         this.name=name;
    42         this.pool=pool;
    43     }
    44     public void run(){
    45         int i=0;
    46         while(true){
    47             int i=pool.remove();
    48             try{
    49                 
    50                 Thread.sleep(100);
    51             }catch(Exception e){
    52                 e.printStackTrace();
    53             }
    54             System.out.println("消费"+i);
    55             
    56         }
    57         
    58     }
    59 }
    60 class Pool{
    61     private java.util.List<Integer> list=new java.util.ArrayList<Integer>();
    62     int Max=100;
    63     //增加元素
    64     public void add(int n){
    65         synchronized(this){
    66             try{
    67                 while(list.size()>=Max){
    68                     this.wait();
    69                 }
    70                 list.add(n);
    71                 System.out.println("剩余库存"+list.size());
    72                 notifyAll();
    73                 
    74             }catch(Exception e){
    75                 e.printStackTrace();
    76             }
    77         }
    78         
    79     }
    80     //删除元素
    81     public void remove(){
    82         // int i;
    83         synchronized(this){
    84             try{
    85                 
    86                 while(list.size()==0){
    87                     this.wait();
    88                 }
    89                 
    90             }catch(Exception e){
    91                 e.printStackTrace();
    92             }
    93         
    94             int i=list.remove(0);
    95                 notify();
    96         }
    97         
    98     }
    99 }

    3、

     1 /**
     2 100个馒头,40个工人吃,每个工人最多吃3个馒头,使用多线程给出所有工人吃馒头情况
     3 */
     4 //定义一个篮子
     5 class Bastket{
     6     private int count =100;//馒头总个数
     7         public int getManTou(){
     8             synchronized(this){//锁旗标,以篮子作为参照物
     9             int tem=count;
    10             count=count-1;
    11             return tem>0?tem:0;//三元运算符
    12             }
    13         }
    14     
    15 }
    16 class Worker extends Thread{
    17     private String name;
    18     private Bastket bas;
    19     private int MAX=3;//最多吃3个
    20     int num=0;//吃的馒头数
    21     public Worker(){};
    22     public Worker(String name,Bastket bas){
    23         this.name=name;
    24         this.bas=bas;
    25     }
    26     public void run(){
    27         while(true){
    28             if(num>=3){
    29                 return;
    30             }
    31             int no=bas.getManTou();//剩余馒头个数
    32             if(no==0){
    33                 return;
    34             }
    35             num++;
    36             System.out.println(name+" 吃的第"+num+"个馒头");
    37         }
    38     }
    39 }
    40 class SynDemo{
    41     public static void main(String[]args){
    42         Bastket bas=new Bastket();
    43         for(int i=1;i<=40;i++){
    44             new Worker("worker--"+i,bas).start();
    45         }
    46     }
    47 }

    4、

     1 class Syn{
     2     public static void main(String[]args){
     3         Saler s1=new Saler("张三");
     4         Saler s2=new Saler("王二");
     5         Saler s3=new Saler("李四");
     6         Saler s4=new Saler("麻子");
     7         s1.start();
     8         s2.start();
     9         s3.start();
    10         s4.start();
    11         
    12     }
    13 }
    14 class Saler extends Thread{
    15     static Object lock=new Object();//锁旗标
    16     private String name;
    17     static int tickets=50;//票数
    18     public Saler(){}
    19     public Saler(String name){
    20         this.name=name;
    21     }
    22     public void run(){
    23         
    24         while(true){
    25             int t=getTicket();
    26             if(t==0){
    27                 return;
    28             }else{
    29                 System.out.println(name+"取走了第"+t+"张票");
    30             }
    31         }
    32     }
    33     public int getTicket(){
    34         synchronized(lock){
    35             int t=tickets;
    36             tickets=tickets-1;
    37             return t<1?0:t;
    38         }
    39     }    
    40 }
     1 /**
     2  *     蜜蜂是生产者,100蜜蜂,2头熊。
     3     蜜蜂每次生产蜂蜜量是1.
     4     篮子的容量是100.
     5     熊在蜂蜜量超过20的时候,一次性吃掉所有蜂蜜。
     6     通过多线程模拟场景。
     7  */
     8 public class BeeBearMain {
     9 
    10     public static void main(String[] args) {
    11         Basket basket = new Basket();
    12         for(int i=1;i<=100;i++){
    13             new Bee(basket,"小蜜蜂"+i).start();
    14         }
    15         Bear b1=new Bear("熊大", basket);
    16         Bear b2=new Bear("熊二", basket);
    17         b1.start();
    18         b2.start();
    19     }
    20 }
    21 
    22 public class Bear extends Thread {
    23     private String name;
    24     private Basket bk;
    25     public Bear(String name, Basket bk) {
    26         super();
    27         this.name = name;
    28         this.bk = bk;
    29     }
    30     public void run() {
    31         while (true) {
    32             synchronized (bk) {
    33                 while (bk.capacity <= 20) {
    34                     try {
    35                         bk.wait();
    36                     } catch (InterruptedException e) {
    37                         e.printStackTrace();
    38                     }
    39                 }
    40                 int tem = bk.capacity;
    41                 bk.capacity = 0;
    42                 bk.notifyAll();
    43                 System.out.println(name + "吃完了" + tem + "蜂蜜");
    44             }
    45             yield();
    46         }
    47     }
    48 }
    49 
    50 public class Bee extends Thread {
    51     private Basket bk;
    52     private String name;
    53 
    54     public Bee(Basket bk, String name) {
    55         super();
    56         this.bk = bk;
    57         this.name = name;
    58     }
    59     @Override
    60     public void run() {
    61         while (true) {
    62             synchronized (bk) {
    63                 while (bk.capacity >= bk.MAX) {
    64                     try {
    65                         bk.wait();
    66                     } catch (InterruptedException e) {
    67                         e.printStackTrace();
    68                     }
    69                 }
    70                 bk.capacity++;
    71                 bk.notifyAll();
    72             }
    73                 int tem = bk.capacity;
    74                 System.out.println(name + "增加了蜂蜜,当前蜂蜜容量为:" + tem);
    75         }
    76     }
    77 }
    78 
    79 public class Basket {
    80     public static final int MAX = 100;// 篮子最大容量
    81     public static int capacity = 0;// 篮子的目前容量
    82 }
  • 相关阅读:
    ORACLE函数<四>
    Oracle中的伪列<三>
    PL/SQL<八>函数
    invoice
    quite
    做人小结
    wsdl 学习笔记
    name, middle name, first name, last name
    小感叹
    qualified、quantity
  • 原文地址:https://www.cnblogs.com/yihaifutai/p/6792999.html
Copyright © 2011-2022 走看看