外观
多线程
2171字约7分钟
2025-06-20
线程
属性
守护
/**
* 守护线程例子:主线程关闭 -> 子线程关闭
*/
public class DaemonDemo {
public static class T1 extends Thread{
@Override
public void run() {
while (true) {
System.out.println("I am alive");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new T1();
thread.setDaemon(true);
thread.start();
Thread.sleep(5000);
}
}优先级
/**
* 线程优先权:优先级大先执行
*/
public class PriorityDemo {
public static class HightPriority extends Thread {
static int count = 0;
@Override
public void run() {
while (true) {
synchronized (PriorityDemo.class) {
count ++;
if (count > 1000000) {
System.out.println("HightPriority is complete");
break;
}
}
}
}
}
public static class LowPriority extends Thread {
static int count = 0;
@Override
public void run() {
while (true) {
synchronized (PriorityDemo.class) {
count ++;
if (count > 1000000) {
System.out.println("LowPriority is complete");
break;
}
}
}
}
}
public static void main(String[] args) {
Thread high = new HightPriority();
Thread low = new LowPriority();
high.setPriority(Thread.MAX_PRIORITY);
low.setPriority(Thread.MIN_PRIORITY);
low.start();
high.start();
}
}等待、通知
/**
* 等待线程:主线程等待子线程执行完再执行
*/
public class JoinDemo {
public volatile static int i = 0;
public static class T1 extends Thread {
public void run() {
while (i < 10000) {
i++;
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new T1();
thread.start();
thread.join();
System.out.println(i);
}
}通知
/**
* 线程等待、通知
* 适用情况:一个线程中有一个子任务,子任务执行结束再继续
*/
public class WNDemo {
final static Object object = new Object();
public static class T1 extends Thread {
public void run() {
synchronized (object) {
System.out.println("T1 start " + System.currentTimeMillis());
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("T1 end " + System.currentTimeMillis());
}
}
}
public static class T2 extends Thread {
public void run() {
synchronized (object) {
System.out.println("T2 start " + System.currentTimeMillis());
object.notify();
System.out.println("T2 end " + System.currentTimeMillis());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Thread t1 = new T1();
Thread t2 = new T2();
t1.start();
t2.start();
}
}对象锁
/**
* 线程执行方法同步(对象锁):不同线程执行同一代码段不并行
*/
public class SyncDemo implements Runnable {
static SyncDemo syncDemo = new SyncDemo();
static int i = 0;
public synchronized void increase() {
i++;
}
@Override
public void run() {
for (int j = 0; j < 10000; j++) {
increase();
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(syncDemo);
Thread t2 = new Thread(syncDemo);
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println(i);
}
}创建
方式1
/**
* 创建线程
* 方式:继承 Thread
*/
public class CreateThread1 extends Thread {
@Override
public void run() {
super.run();
}
public static void main(String[] args) {
Thread thread = new CreateThread1();
thread.start();
Thread.yield(); // 让出CPU
}
}方式2
/**
* 创建线程
* 方式:实现 Runnable
*/
public class CreateThread2 implements Runnable {
@Override
public void run() {
System.out.println("开始运行这个线程");
}
public static void main(String[] args) {
Thread thread = new Thread();
thread.start();
Thread.yield(); // 让出CPU
}
}方式3
/**
* 创建线程
* 方式:CompletableFuture 创建
*/
public class CreateThread3 {
public void exec() throws ExecutionException, InterruptedException {
CompletableFuture completableFuture1 = CompletableFuture
.runAsync(() -> {
System.out.println("方法1 开始");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("方法1 执行");
});
CompletableFuture completableFuture2 = CompletableFuture
.runAsync(() -> {
System.out.println("方法2 开始");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("方法2 执行");
});
CompletableFuture completableFuture3 = CompletableFuture
.runAsync(() -> {
System.out.println("方法3 开始");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("方法3 执行");
});
List<CompletableFuture> completableFutureList = new ArrayList<CompletableFuture>();
completableFutureList.add(completableFuture1);
completableFutureList.add(completableFuture2);
completableFutureList.add(completableFuture3);
for (CompletableFuture completableFuture : completableFutureList) {
completableFuture.get();
}
}
@Test
public void test() {
try {
exec();
} catch (Exception e) {
e.printStackTrace();
}
}
}方式4
/**
* 创建线程
* 方式:通过FutureTask、Callable 创建
* 说明:
* (1)创建Callable接口的实现类,并重写call()方法,该call()方法作为线程的执行体,且有返回值
* (2)创建了Callable接口的实现类的实例,并用FutureTask()方法包装对象,该FutureTask()对象实现了将对象的返回值包装的功能
* (3)使用FutureTask对象将Thread对象的target,创建并启动线程
* (4)调用FutureTask对象的get()方法获得子线程执行结束后的返回值
*/
public class CreateThread4 implements Callable<Integer> {
@Override
public Integer call() throws Exception { // 重写Callable接口中的call()方法
int i = 0;
for (; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
return i;
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
// 创建Callable的对象
CreateThread4 thread4 = new CreateThread4();
FutureTask<Integer> ft = new FutureTask<Integer>(thread4);
for (int i = 0; i < 100; i++) {
// 返回值主线程的名称和执行代号
System.out.println(Thread.currentThread().getName() + " " + i);
if (i == 20) {
new Thread(ft, "Callable线程").start();
}
}
try {
System.out.println("子线程的返回值" + ft.get());
} catch (Exception e) {
e.printStackTrace();
}
}
}方式5
/**
* 创建线程
* 方式:线程组
*/
public class CreateThread5 implements Runnable {
@Override
public void run() {
String groupName = Thread.currentThread().getThreadGroup().getName();
String name = Thread.currentThread().getName();
while (true) {
System.out.println("I am " + groupName + " " + name);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ThreadGroup threadGroup = new ThreadGroup("ThreadGroup1");
Thread thread1 = new Thread(threadGroup, new CreateThread5(), "thread1");
Thread thread2 = new Thread(threadGroup, new CreateThread5(), "thread2");
thread1.start();
thread2.start();
System.out.println(threadGroup.activeCount());
threadGroup.list();
}
}分组
线程组
/**
* 线程组
*/
public class ThreadGroupName implements Runnable {
@Override
public void run() {
String groupName = Thread.currentThread().getThreadGroup().getName();
String name = Thread.currentThread().getName();
while (true) {
System.out.println("I am " + groupName + " " + name);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ThreadGroup threadGroup = new ThreadGroup("ThreadGroup1");
Thread thread1 = new Thread(threadGroup, new ThreadGroupName(), "thread1");
Thread thread2 = new Thread(threadGroup, new ThreadGroupName(), "thread2");
thread1.start();
thread2.start();
System.out.println(threadGroup.activeCount());
threadGroup.list();
}
}方法
中断线程
/**
* 中断线程
*/
public class InterruptedThread implements Runnable {
@Override
public void run() {
while (true) {
if (Thread.currentThread().isInterrupted()) {
System.out.println("Interrupted");
break;
}
try {
Thread.sleep(2000);
} catch (Exception e) {
System.out.println("Error When sleep");
Thread.currentThread().interrupt();
}
Thread.yield();
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new InterruptedThread());
thread.start();
Thread.sleep(2000);
thread.interrupt(); // 中断
}
}问题
HashMap多线程问题
public class HashMapProblem implements Callable<Integer> {
private static ExecutorService exec = Executors.newFixedThreadPool(10);
private static Map<Integer, Integer> results = new HashMap<Integer, Integer>();
@Override
public Integer call() throws Exception {
for (int i = 0; i < 1000; i++) {
results.put(i, i);
}
/*
Thread.sleep(100);
for (int i = 0; i < 1000; i++) {
results.remove(i);
}
*/
System.out.println(" ---- " + Thread.currentThread().getName() + " " + results.size());
return results.get(1);
}
public static void main(String[] args) throws InterruptedException {
Stopwatch stopwatch = new Stopwatch();
for (int i = 0; i < 200; i++) {
HashMapProblem hashMapProblem = new HashMapProblem();
exec.submit(hashMapProblem);
}
exec.shutdown();
while(true){
if(exec.isTerminated()){
System.out.println("所有的子线程都结束了!");
break;
}
}
System.out.println(stopwatch.elapsedTime());
}
}ArrayList多线程问题
/**
* ArrayList多线程问题
*/
public class ArrayListMultiThread {
static ArrayList<Integer> arrayList = new ArrayList<Integer>(10); // 线程不安全
static Vector<Integer> vector = new Vector<Integer>(10); // 线程安全
public static class AddThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 1000000; i++) {
vector.add(i);
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new AddThread());
Thread t2 = new Thread(new AddThread());
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(vector.size());
}
}锁
重入锁
/**
* 重入锁(显性的 synchronized):代码段线程安全
*/
public class ReenterLock implements Runnable{
public static ReentrantLock lock = new ReentrantLock(true);
public static int i = 0;
@Override
public void run() {
for (int j = 0; j < 100; j++) {
lock.lock();
try {
i++;
} finally {
lock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
ReenterLock reenterLock = new ReenterLock();
Thread t1 = new Thread(reenterLock);
Thread t2 = new Thread(reenterLock);
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println(i);
}
}重入锁条件
/**
* 重入锁条件:暂停、唤醒
*/
public class ReenterLockCondition implements Runnable {
public static ReentrantLock lock = new ReentrantLock();
public static Condition condition = lock.newCondition();
@Override
public void run() {
try {
lock.lock();
System.out.println("Thread is wait");
condition.await();
System.out.println("Thread is going on");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
ReenterLockCondition reenterLockCondition = new ReenterLockCondition();
Thread t1 = new Thread(reenterLockCondition);
t1.start();
Thread.sleep(2000);
lock.lock();
System.out.println("Thread is notify");
condition.signal();
lock.unlock();
}
}信号量
/**
* 信号量:线程池中每次执行的线程数
*/
public class SemapDemo implements Runnable {
final Semaphore semaphore = new Semaphore(5); // 信号量
@Override
public void run() {
try {
semaphore.acquire();
Thread.sleep(2000);
System.out.println(Thread.currentThread().getId() + ":done!");
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(20); // 创建线程池
final SemapDemo demo = new SemapDemo();
for (int i = 0; i < 20; i++) {
executorService.submit(demo); // 每次创建的信号量
}
}
}读写锁
/**
* 读写锁:读并行、写不并行,提升效率
*/
public class ReadWriteLockDemo {
private static Lock lock = new ReentrantLock();
private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private static Lock readLock = readWriteLock.readLock();
private static Lock writeLock = readWriteLock.writeLock();
private int value;
private static Stopwatch stopwatch = new Stopwatch();
public Object handleRead(Lock lock) {
try {
lock.lock();
Thread.sleep(1000);
System.out.println("读执行时长:" + stopwatch.elapseTime());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return value;
}
public void handleWrite(Lock lock, int index) {
try {
lock.lock();
Thread.sleep(1000);
value = index;
System.out.println("写执行时长:" + stopwatch.elapseTime());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
final ReadWriteLockDemo demo = new ReadWriteLockDemo();
Runnable readRunbale = new Runnable() {
@Override
public void run() {
demo.handleRead(readLock);
//demo.handleRead(lock);
}
};
Runnable writeRunbale = new Runnable() {
@Override
public void run() {
demo.handleWrite(writeLock, new Random().nextInt());
//demo.handleWrite(lock, new Random().nextInt());
}
};
for (int i = 0; i < 10; i++) {
Thread t1 = new Thread(readRunbale);
t1.start();
}
for (int i = 0; i < 10; i++) {
Thread t2 = new Thread(writeRunbale);
t2.start();
}
}
}倒计时器(线程池执行完成指定线程后执行)
/**
* 倒计时:线程一个个执行,线程池中的执行完成指定线程后在执行主线程
*/
public class CountDownLatchDemo implements Runnable {
static final CountDownLatch end = new CountDownLatch(5);
static final CountDownLatchDemo demo = new CountDownLatchDemo();
@Override
public void run() {
try {
Thread.sleep(new Random().nextInt(10) * 1000);
System.out.println("check complete");
end.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
ExecutorService exec = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
exec.submit(demo);
}
end.await(); // 等待检查
System.out.println("Fire!");
exec.shutdown();
}
}循环栏珊
/**
* 循环栏珊:一种线程的集合
*/
public class CyclicBarrierDemo {
public static class Soldier implements Runnable {
private String soldier;
private final CyclicBarrier cyclicBarrier;
public Soldier(CyclicBarrier cyclicBarrier, String soldierName) {
this.cyclicBarrier = cyclicBarrier;
this.soldier = soldierName;
}
@Override
public void run() {
try {
cyclicBarrier.await();
doWork();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
void doWork() {
try {
Thread.sleep(Math.abs(new Random().nextInt()%10000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(soldier + ":任务完成");
}
}
public static class BarrierRun implements Runnable {
boolean flag;
int N;
public BarrierRun(boolean flag, int N) {
this.flag = flag;
this.N = N;
}
@Override
public void run() {
if (flag) {
System.out.println("司令:[士兵" + N + "个,任务完成!]");
} else {
System.out.println("司令:[士兵" + N + "个,集合完毕!]");
flag = true;
}
}
}
public static void main(String[] args) {
final int N = 10;
Thread[] allSoldier = new Thread[N];
boolean flag = false;
CyclicBarrier cyclicBarrier = new CyclicBarrier(N, new BarrierRun(flag, N));
System.out.println("集合队伍!");
for (int i = 0; i < N; ++i) {
System.out.println("士兵" + i + "报道!");
allSoldier[i] = new Thread(new Soldier(cyclicBarrier, "士兵" + i));
allSoldier[i].start();
}
}
}线程阻塞
/**
* 线程阻塞:不需要获取对象
*/
public class LockSupportDemo {
public static Object u = new Object();
static ChangeObjectThread t1 = new ChangeObjectThread("t1");
static ChangeObjectThread t2 = new ChangeObjectThread("t2");
public static class ChangeObjectThread extends Thread {
public ChangeObjectThread (String name) {
super.setName(name);
}
@Override
public void run() {
synchronized (u) {
System.out.println("in: " + getName());
LockSupport.park();
}
}
}
public static void main(String[] args) throws InterruptedException {
t1.start();
Thread.sleep(100);
t2.start();
LockSupport.unpark(t1);
LockSupport.unpark(t2);
t1.join();
t2.join();
}
}