编写java并发代码案例
时间: 2024-01-22 21:03:07 浏览: 76
很高兴回答你的问题。以下是一个简单的Java并发代码案例:
```java
public class MyThread implements Runnable {
private int count = 0;
public void run() {
for (int i = 0; i < 5; i++) {
increment();
}
}
public synchronized void increment() {
count++;
System.out.println(Thread.currentThread().getName() + ",count = " + count);
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread thread1 = new Thread(myThread, "Thread 1");
Thread thread2 = new Thread(myThread, "Thread 2");
thread1.start();
thread2.start();
}
}
```
这段代码创建了一个实现了Runnable接口的MyThread类。MyThread类有一个共享变量count和一个使用synchronized关键字实现了线程安全的increment方法。在main方法中,它创建了两个线程来执行MyThread的run方法。这两个线程并发执行increment方法,保证了count变量的线程安全性。输出结果如下:
```
Thread 1,count = 1
Thread 1,count = 2
Thread 1,count = 3
Thread 1,count = 4
Thread 1,count = 5
Thread 2,count = 6
Thread 2,count = 7
Thread 2,count = 8
Thread 2,count = 9
Thread 2,count = 10
```
希望这个例子可以对你有所帮助!
阅读全文