Java多线程实战:轻松入门的10个实用Demo解析

多线程编程在Java中是一个重要的概念,它允许开发者编写能够同时执行多个任务的程序。以下是10个实用的多线程Demo,可以帮助初学者轻松入门Java多线程编程。
Demo 1: 创建并启动线程
public class SimpleThread extends Thread {
@Override
public void run() {
System.out.println(“线程 ” + Thread.currentThread().getName() + ” 正在运行”);
}

public static void main(String[] args) {
Thread t = new SimpleThread();
t.start();
}
}
在这个Demo中,我们创建了一个继承自
Thread
类的
SimpleThread
,并覆盖了
run
方法。在
main
方法中,我们创建了一个
SimpleThread
实例并启动它。
Demo 2: 使用Runnable接口
public class RunnableDemo implements Runnable {
@Override
public void run() {
System.out.println(“线程 ” + Thread.currentThread().getName() + ” 正在运行”);
}

public static void main(String[] args) {
Thread t = new Thread(new RunnableDemo());
t.start();
}
}
在这个Demo中,我们使用
Runnable
接口而不是继承
Thread
类。这种方式更灵活,因为你可以将同一个
Runnable
实例传递给多个线程。
Demo 3: 线程休眠
public class SleepDemo implements Runnable {
@Override
public void run() {
try {
System.out.println(“线程 ” + Thread.currentThread().getName() + ” 正在休眠”);
Thread.sleep(1000);
System.out.println(“线程 ” + Thread.currentThread().getName() + ” 唤醒”);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
Thread t = new Thread(new SleepDemo());
t.start();
}
}
在这个Demo中,我们演示了如何使线程休眠一段时间,使用
Thread.sleep
方法。
Demo 4: 线程优先级
public class PriorityDemo implements Runnable {
@Override
public void run() {
System.out.println(“线程 ” + Thread.currentThread().getName() + ” 优先级: ” + Thread.currentThread().getPriority());
}

public static void main(String[] args) {
Thread t1 = new Thread(new PriorityDemo(), “高优先级线程”);
t1.setPriority(Thread.MAX_PRIORITY);
Thread t2 = new Thread(new PriorityDemo(), “低优先级线程”);
t2.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
}
}
在这个Demo中,我们设置了两个线程的不同优先级,并打印出它们的优先级。
Demo 5: 同步块
public class SynchronizedBlockDemo implements Runnable {
private static int count = 0;

@Override
public void run() {
for (int i = 0; i < 10; i++) { synchronized (SynchronizedBlockDemo.class) { count++; System.out.println(Thread.currentThread().getName() + " - " + count); } } } public static void main(String[] args) { Thread t1 = new Thread(new SynchronizedBlockDemo(), "线程1"); Thread t2 = new Thread(new SynchronizedBlockDemo(), "线程2"); t1.start(); t2.start(); } } 在这个Demo中,我们使用同步块来确保在多线程环境中对共享资源的访问是线程安全的。 Demo 6: 线程通信 public class ThreadCommunicationDemo implements Runnable { private volatile boolean flag = true; @Override public void run() { while (flag) { System.out.println(Thread.currentThread().getName() + " 正在运行"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + " 已停止"); } public static void main(String[] args) { Thread t = new Thread(new ThreadCommunicationDemo()); t.start(); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } t.interrupt(); } } 在这个Demo中,我们展示了如何通过中断标志来停止线程。 Demo 7: 线程池 import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPoolDemo implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName() + " 正在执行任务"); } public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(5); for (int i = 0; i < 10; i++) { executor.execute(new ThreadPoolDemo()); } executor.shutdown(); } } 在这个Demo中,我们使用了线程池来管理线程,这样可以提高性能并减少线程创建和销毁的开销。 Demo 8: 生产者-消费者问题 import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class ProducerConsumerDemo { private static BlockingQueue queue = new ArrayBlockingQueue<>(5);

public static class Producer implements Runnable {
@Override
public void run() {
try {
for (int i = 0; i < 20; i++) { queue.put(i); System.out.println("生产者 " + Thread.currentThread().getName() + " 生产了: " + i); Thread.sleep(100); } } catch (InterruptedException e) { e.printStackTrace(); } } } public static class Consumer implements Runnable { @Override public void run() { try { while (true) { Integer take = queue.take(); System.out.println("消费者 " + Thread.currentThread().getName() + " 消费了: " + take); Thread.sleep(100); } } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { Thread producerThread = new Thread(new Producer(), "生产者线程"); Thread consumerThread = new Thread(new Consumer(), "消费者线程"); producerThread.start(); consumerThread.start(); } } 在这个Demo中,我们使用 BlockingQueue 来实现生产者-消费者问题。 Demo 9: 线程安全的队列 import java.util.concurrent.ConcurrentLinkedQueue; public class ConcurrentQueueDemo { private static ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue<>();

public static void main(String[] args) {
for (int i = 0; i < 10; i++) { queue.add(i); } System.out.println("队列元素: " + queue); } } 在这个Demo中,我们使用 ConcurrentLinkedQueue 来实现线程安全的队列。 Demo 10: 线程安全的集合 import java.util.Collections; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; public class ConcurrentSetDemo { private static Set set = Collections.synchronizedSet(new CopyOnWriteArraySet<>());

public static void main(String[] args) {
set.add(“元素1”);
set.add(“元素2”);
set.add(“元素3”);
System.out.println(“集合元素: ” + set);
}
}
在这个Demo中,我们使用
CopyOnWriteArraySet
来实现线程安全的集合。
以上10个实用的多线程Demo涵盖了Java多线程编程的各个方面,从基础概念到高级应用。通过这些示例,初学者可以逐步掌握多线程编程的技巧,并在实际项目中应用这些知识。