java 如何秒速写一个线程启动
Posted qianbo_insist
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 如何秒速写一个线程启动相关的知识,希望对你有一定的参考价值。
线程
java 的线程相对c,c++来说基本是类似的,尤其是使用lamba都是非常快速的就能启动一个线程,相对于使用api来说,简化了很多。有几种方式可以使用:
1、使用静态内部类
java的线程类可以直接从Runnable上继承,实现 run()函数即可
static Map<String,String> v_map = new ConcurrentHashMap<String,String>();
static class th1 implements Runnable{
public void run() {
for(int i = 0; i < 10; i ++) {
v_map.put(String.valueOf(i), String.valueOf(i));
}
//遍历值
for (String value : v_map.values()) {
System.out.println("thread1 value = " + value);
}
}
}
调用,直接new Thread ,调用方法start().
new Thread(new th1()).start();
2、直接new Thread
这种方式更为方便,不用写一个class,直接启动线程即可,如果没有其他需要交互的变量和方法,这种方式更为直接。
new Thread(new Runnable(){
public void run() {
for (String value : v_map.values()) {
System.out.println("thread2 value = " + value);
}
}
}).start();
3、lamba简化写法
new Thread(()->{
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<String,String> v_map = new ConcurrentHashMap<String,String>();
static class th1 implements Runnable{
public void run() {
for(int i = 0; i < 10; i ++) {
v_map.put(String.valueOf(i), String.valueOf(i));
}
//遍历值
for (String value : v_map.values()) {
System.out.println("thread1 value = " + value);
}
}
}
public static void main(String[] args) {
new Thread(new th1()).start();
new Thread(new Runnable(){
public void run() {
for (String value : v_map.values()) {
System.out.println("thread2 value = " + value);
}
}
}).start();
//简化 lambda
new Thread(()->{
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
以上是关于java 如何秒速写一个线程启动的主要内容,如果未能解决你的问题,请参考以下文章
newCacheThreadPool()newFixedThreadPool()newScheduledThreadPool()newSingleThreadExecutor()自定义线程池(代码片段