zoukankan      html  css  js  c++  java
  • 多线程10--线程间实时通信--耗性能的轮询

    1.

     1 public class ListAdd2 {
     2     private volatile static List list = new ArrayList();
     3     
     4     public void add(){
     5         list.add("hello");
     6     }
     7     
     8     public int size(){
     9         return list.size();
    10     }
    11     
    12     public static void main(String[] args) {
    13         final ListAdd2 list1 = new ListAdd2();
    14         Thread t1 = new Thread(new Runnable() {
    15             @Override
    16             public void run() {
    17                 try {
    18                     for (int i = 0; i < 10; i++) {
    19                         list1.add();
    20                         System.out.println(Thread.currentThread().getName()+"添加了一个元素...");
    21                         Thread.sleep(100);
    22                     }
    23                 } catch (Exception e) {
    24                     e.printStackTrace();
    25                 }
    26                 
    27             }
    28         }, "t1");
    29         
    30         Thread t2 = new Thread(new Runnable() {
    31             @Override
    32             public void run() {
    33                 while(true){ //一直轮询,很耗性能
    34                     if(list1.size() == 5){
    35                         System.out.println(Thread.currentThread().getName()+"list大小为5,线程停止");
    36                         throw new RuntimeException();
    37                     }
    38                 }
    39             }
    40         }, "t2");
    41         
    42         t1.start();
    43         t2.start();
    44     }
    45     /*
    46     t1添加了一个元素...
    47     t1添加了一个元素...
    48     t1添加了一个元素...
    49     t1添加了一个元素...
    50     t1添加了一个元素...
    51     t2list大小为5,线程停止
    52     Exception in thread "t2" java.lang.RuntimeException
    53         at com.bjsxt.base.thread06.ListAdd2$2.run(ListAdd2.java:41)
    54         at java.lang.Thread.run(Thread.java:744)
    55     t1添加了一个元素...
    56     t1添加了一个元素...
    57     t1添加了一个元素...
    58     t1添加了一个元素...
    59     t1添加了一个元素...
    60     */
    61 }
    View Code
  • 相关阅读:
    MVC--全选反选
    文件上传(表单,Ajax)、文件下载
    Java的一些细节语法(不定时更新。。。)
    并发基础知识
    Linux基本命令操作
    Linux基本操作和自己动手组装服务器
    VMware虚拟机和CentOS系统的安装过程
    安装操作系统
    中间件介绍
    wifi破解
  • 原文地址:https://www.cnblogs.com/bravolove/p/7944605.html
Copyright © 2011-2022 走看看