线程
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
