并发控制挑战:Java多线程编程实例
在Java中,多线程编程为解决并发问题提供了工具。以下是一个简单的Java多线程示例:
- 创建类(假设我们创建一个名为
CounterThread
的类)
public class CounterThread extends Thread {
private int count = 0;
public CounterThread(String name) {
super(name);
}
// 线程运行的方法
@Override
public void run() {
while (true) { // 无限循环,模拟持续计数
count++;
try {
// 模拟耗时操作,线程在此等待
Thread.sleep(100); // 100毫秒的休眠
} catch (InterruptedException e) {
e.printStackTrace();
break; // 线程中断,退出循环
}
}
}
// 获取当前计数
public int getCount() {
return count;
}
}
- 创建线程并启动(创建一个
CounterThread
实例,并开始它的运行)
public class Main {
public static void main(String[] args) {
CounterThread counterThread = new CounterThread("Counting Thread");
// 启动线程
counterThread.start();
try {
// 线程执行完毕后,获取计数值
int count = counterThread.getCount();
System.out.println("Final Count: " + count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
以上代码示例创建了一个名为CounterThread
的线程类。这个线程会无限循环,模拟计数器的行为。在主线程中启动这个线程,并在执行完毕后获取最终的计数值。
还没有评论,来说两句吧...