java多线程是一个很重要的内容,必须好好理解,
以下是十个Java多线程案例,每个案例都有相应的示例代码:
创建线程
public class MyThread extends Thread {
public void run() {
// 线程执行的操作
}
}
MyThread thread = new MyThread();
thread.start();
实现Runnable接口
public class MyTask implements Runnable {
public void run() {
// 线程执行的操作
}
}
Thread thread = new Thread(new MyTask());
thread.start();
实现Callable接口
public class MyTask implements Callable<Integer> {
public Integer call() {
// 线程执行的操作
return 1;
}
}
FutureTask<Integer> futureTask = new FutureTask<>(new MyTask());
Thread thread = new Thread(futureTask);
thread.start();
int result = futureTask.get();
线程池
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < 100; i++) {
executorService.execute(() -> {
// 线程执行的操作
});
}
executorService.shutdown();
线程同步
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
// 线程中调用increment方法
Counter counter = new Counter();
counter.increment();
线程间通信
class Message {
private String content;
private boolean empty = true;
public synchronized String read() {
while (empty) {
try {
wait();
} catch (InterruptedException e) {
// 异常处理
}
}
empty = true;
notifyAll();
return content;
}
public synchronized void write(String message) {
while (!empty) {
try {
wait();
} catch (InterruptedException e) {
// 异常处理
}
}
empty = false;
this.content = message;
notifyAll();
}
}
class Writer implements Runnable {
private Message message;
public Writer(Message message) {
this.message = message;
}
public void run() {
String[] messages = {“message1”, “message2”, “message3”, “message4”};
for (String message : messages) {
this.message.write(message);
}
this.message.write(“Finished”);
}
}
class Reader implements Runnable {
private Message message;
public Reader(Message message) {
this.message = message;
}
public void run() {
for (String message = this.message.read(); !message.equals(“Finished”); message = this.message.read()) {
System.out.println(message);
}
}
}
Message message = new Message();
new Thread(new Writer(message)).start();
new Thread(new Reader(message)).start();
线程优先级
class MyThread extends Thread {
public void run() {
// 线程执行的操作
}
}
MyThread thread1 = new MyThread();
thread1.setPriority(Thread.MIN_PRIORITY);
MyThread thread2 = new MyThread();
thread2.setPriority(Thread.MAX_PRIORITY);
线程睡眠
try {
Thread.sleep(1000); // 线程睡眠1秒
} catch (InterruptedException e) {
// 异常处理
}
线程中断
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
// 线程执行的操作
}
});
thread.start();
thread.interrupt(); // 终止线程
线程局部变量
class MyThread implements Runnable {
private ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
public void run() {
threadLocal.set((int) (Math.random() * 100));
System.out.println(Thread.currentThread().getName() + " : " + threadLocal.get());
}
}
MyThread thread = new MyThread();
new Thread(thread).start();
new Thread(thread).start();
希望这些多线程案例和示例代码能够帮助您更好地理解Java多线程编程。