创建Java多线程程序主要有两种方法:继承Thread类和实现Runnable接口。以下是这两种方法的详细步骤和示例代码。
创建一个类继承Thread类:
class MyThread extends Thread {
@Override
public void run() {
// 线程执行的代码
System.out.println("线程正在运行");
}
}
创建线程对象并启动线程:
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程
}
}
创建一个类实现Runnable接口:
class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的代码
System.out.println("线程正在运行");
}
}
创建线程对象并启动线程:
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start(); // 启动线程
}
}
在多线程编程中,同步是一个重要的概念,用于控制多个线程对共享资源的访问。Java提供了多种同步机制,如synchronized关键字和Lock接口。
synchronized关键字class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
class IncrementThread extends Thread {
private Counter counter;
public IncrementThread(Counter counter) {
this.counter = counter;
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
IncrementThread thread1 = new IncrementThread(counter);
IncrementThread thread2 = new IncrementThread(counter);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println("Final count: " + counter.getCount());
}
}
Lock接口import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Counter {
private int count = 0;
private final Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
}
class IncrementThread extends Thread {
private Counter counter;
public IncrementThread(Counter counter) {
this.counter = counter;
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
IncrementThread thread1 = new IncrementThread(counter);
IncrementThread thread2 = new IncrementThread(counter);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println("Final count: " + counter.getCount());
}
}
以上是创建Java多线程程序的基本方法和同步机制的示例。根据具体需求选择合适的方法和同步机制来实现多线程程序。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。