示例示例Java保证线程安全的方法有很多,主要有以下几种:使用关键字:关键字可以在任何对象及方法上加锁,当它锁定一个方法或者一个代码块的时候,同一时刻最多只有一个线程执行这段代码。
Java保证线程安全的方法有很多,主要有以下几种:
1. 使用synchronized关键字:Synchronized关键字可以在任何对象及方法上加锁,当它锁定一个方法或者一个代码块的时候,同一时刻最多只有一个线程执行这段代码。
代码示例:
public class ThreadSafeExample {
private int count = 0;
public synchronized void increment() {
count++;
}
public static void main(String[] args) {
ThreadSafeExample example = new ThreadSafeExample();
example.doWork();
}
public void doWork() {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
increment();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
increment();
}
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Count is: " + count);
}
}
2. 使用Atomic类:Atomic类提供了一些原子操作,可以在高并发的情况下保证变量的正确更新。
代码示例:
public class AtomicExample {
private AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.incrementAndGet();
}
public static void main(String[] args) {
AtomicExample example = new AtomicExample();
example.doWork();
}
public void doWork() {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
increment();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
increment();
}
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Count is: " + count);
}
}
3. 使用Lock锁:Lock锁可以替代synchronized关键字,它提供比synchronized更多的功能,比如可以设定超时时间、可中断锁等等。
代码示例:
public class LockExample {
private Lock lock = new ReentrantLock();
private int count = 0;
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.un
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(59条)