1.继承Thread类 2.实现Runnable接口 3.实现callable接口
1.新建 2.就绪 3.运行 4.阻塞 5.死亡
设置优先级增加在cpu那里的权重
用户线程:main() 守护线程:gc() 虚拟机必须确保用户线程执行完毕,不必等待守护线程执行完毕
使用synchronized(object){}时,object为变化的量,默认是this
例子:使用多个线程向数组中添加数据
package com.css.apps.base.dict.service;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* zt
* 2021/6/17
* 14:50
*/
public class TestDemo2 {
/*public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
for (int i = 0; i < 10000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}*/
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
synchronized (list){
list.add(Thread.currentThread().getName());
}
}
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}