深入理解Java的多线程编程问题实例
在Java中,多线程编程主要是通过创建多个线程,使得这些线程能够在同一个进程中并发执行。下面是一个简单的例子,演示了如何创建和使用多线程:
- 创建一个Runnable接口的实现类,如ThreadDemo。
public class ThreadDemo implements Runnable {
private int count = 0;
@Override
public void run() {
for (int i = 0; i < 5; i++) {
synchronized (this) { // 使用synchronized关键字保护共享资源
count++;
System.out.println("Thread " + Thread.currentThread().getName() + " counts: " + count);
if (count >= 10) { // 当计数达到10时,停止线程
break;
}
}
}
}
}
- 创建一个Thread对象,并传入你的Runnable实现类。
public class Main {
public static void main(String[] args) {
ThreadDemo demo = new ThreadDemo();
Thread thread = new Thread(demo); // 创建线程
thread.start(); // 启动线程
try {
thread.join(); // 等待线程完成
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main thread counts: " + demo.count)); // 输出主线程计数
}
}
这个例子中,ThreadDemo类的run方法会在一个新的线程上执行。当计数值达到10时,主线程会等待线程完成并输出最后的计数结果。
还没有评论,来说两句吧...