16.同步类容器Collections.synchronized

voctor动态数组、同步类容器,底层实现基于:Collections.synchronized

 

package demo5; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Vector; /** * Created by liudan on 2017/7/9. */ public class MyThread2 extends Thread { /*同步类容器、动态数组*/ public static void main(String[] args) { /*final Vector<String> ticksts = new Vector<>();*/ List<String> ticksts = Collections.synchronizedList(new ArrayList<String>()); for (int i = 1; i <= 100; i++) { ticksts.add("G1001-火车票-G000X" + i); } for (int i = 1; i <= 10; i++) { new Thread("线程" + i) { @Override public void run() { while (true) { if (ticksts.isEmpty()) break; System.err.println(Thread.currentThread().getName() + "\t" + ticksts.remove(0)); } } }.start(); } } } 输出: 线程001 G1001-火车票-G000X1 线程001 G1001-火车票-G000X2 线程001 G1001-火车票-G000X3 线程001 G1001-火车票-G000X4 线程002 G1001-火车票-G000X5 线程002 G1001-火车票-G000X7 线程001 G1001-火车票-G000X6 线程001 G1001-火车票-G000X9 线程001 G1001-火车票-G000X10 线程002 G1001-火车票-G000X8
x
 
1
package demo5;
2
 
         
3
import java.util.ArrayList;
4
import java.util.Collections;
5
import java.util.List;
6
import java.util.Vector;
7
 
         
8
/**
9
 * Created by liudan on 2017/7/9.
10
 */
11
public class MyThread2 extends Thread {
12
    /*同步类容器、动态数组*/
13
    public static void main(String[] args) {
14
        /*final Vector<String> ticksts = new Vector<>();*/
15
 
         
16
        List<String> ticksts = Collections.synchronizedList(new ArrayList<String>());
17
 
         
18
 
         
19
        for (int i = 1; i <= 100; i++) {
20
            ticksts.add("G1001-火车票-G000X" + i);
21
        }
22
 
         
23
 
         
24
        for (int i = 1; i <= 10; i++) {
25
            new Thread("线程" + i) {
26
                @Override
27
                public void run() {
28
                    while (true) {
29
                        if (ticksts.isEmpty()) break;
30
                        System.err.println(Thread.currentThread().getName() + "\t" + ticksts.remove(0));
31
                    }
32
                }
33
            }.start();
34
        }
35
 
         
36
    }
37
}
38
输出:
39
线程001   G1001-火车票-G000X1
40
线程001   G1001-火车票-G000X2
41
线程001   G1001-火车票-G000X3
42
线程001   G1001-火车票-G000X4
43
线程002   G1001-火车票-G000X5
44
线程002   G1001-火车票-G000X7
45
线程001   G1001-火车票-G000X6
46
线程001   G1001-火车票-G000X9
47
线程001   G1001-火车票-G000X10
48
线程002   G1001-火车票-G000X8



转载于:https://www.cnblogs.com/xxt19970908/p/7302392.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值