对于多线程编程,你理解Java中的synchronized关键字吗?请举例说明。
synchronized
关键字是Java中用于实现线程同步的关键字。它主要用于修饰方法或者代码块,以确保在同一时间只有一个线程能够访问被synchronized
修饰的代码。
以下是一些例子:
修饰方法:
public class Counter {
private int count = 0;
// synchronized method to increment count
public synchronized void increment() {
count++;
}
// example usage: multiple threads can call increment(), but only one thread at a time
public static void main(String[] args) {
Counter counter = new Counter();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
counter.increment();
}
}));
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
counter.increment();
}
}));
thread1.start();
thread2.start();
// wait until both threads finish
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
修饰代码块:
public class PrintCounter {
private int count = 0;
// synchronized code block to print count
public synchronized void printCount() {
System.out.println("Count: " + count);
}
// example usage: multiple threads can call printCount(), but only one thread at a time
public static void main(String[] args) {
PrintCounter counter = new PrintCounter();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
counter.printCount();
}
}));
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
counter.printCount();
}
}));
thread1.start();
thread2.start();
// wait until both threads finish
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
以上例子展示了如何使用
synchronized
关键字来实现线程同步,确保同一时间只有一个线程可以访问共享资源。
还没有评论,来说两句吧...