您当前的位置: 首页 >  Java

qianbo_insist

暂无认证

  • 0浏览

    0关注

    399博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

java 如何秒速写一个线程启动

qianbo_insist 发布时间:2021-07-01 09:33:11 ,浏览量:0

线程

java 的线程相对c,c++来说基本是类似的,尤其是使用lamba都是非常快速的就能启动一个线程,相对于使用api来说,简化了很多。有几种方式可以使用:

1、使用静态内部类

java的线程类可以直接从Runnable上继承,实现 run()函数即可

static Map v_map = new ConcurrentHashMap();

    static class th1 implements Runnable{
		public void run() {
            for(int i = 0; i {
           for (String value : v_map.values()) {
            System.out.println("thread3 value = " + value);
          }
}).start();

()->的写法开始流行了,这样看起来和用起来更简单了是不是? 下面是所有代码,使用ConcurrentHashMap做实验,多个线程同时操作一个ConcurrentHashMap来演示:

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class threadclass {

    static Map v_map = new ConcurrentHashMap();

    static class th1 implements Runnable{


		public void run() {
            for(int i = 0; i {
           for (String value : v_map.values()) {
            System.out.println("thread3 value = " + value);
            }
		}).start();
	}
}

输出: thread1 value = 0 thread1 value = 1 thread1 value = 2 thread1 value = 3 thread1 value = 4 thread2 value = 0 thread2 value = 1 thread1 value = 5 thread2 value = 2 thread2 value = 3 thread1 value = 6 thread2 value = 4 thread2 value = 5 thread1 value = 7 thread1 value = 8 thread2 value = 6 thread2 value = 7 thread1 value = 9 thread2 value = 8 thread2 value = 9 thread3 value = 0 thread3 value = 1 thread3 value = 2 thread3 value = 3 thread3 value = 4 thread3 value = 5 thread3 value = 6 thread3 value = 7 thread3 value = 8 thread3 value = 9

关注
打赏
1663161521
查看更多评论
立即登录/注册

微信扫码登录

0.0375s