Java作为一门面向对象的编程语言,采用JVM的虚拟机方式运行程序,因此Java具有灵活的线程机制。在Java中,多线程机制可以使程序并行执行多个任务,从而提高程序的效率。
线程的创建和启动
Java中的线程可以通过继承Thread类或实现Runnable接口来创建。下面是通过继承Thread类创建并启动线程的一个例子:
public class MyThread extends Thread {
public void run() {
// 执行线程需要完成的任务
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}线程中断
Java中的线程可以被中断,即让一个正在执行的线程停止执行。线程中断是通过调用线程的interrupt()方法来实现的,代码如下:
public class MyThread extends Thread {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// 执行线程需要完成的任务
}
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {}
thread.interrupt();
}
}线程同步
Java中的多线程涉及到竞争条件,即多个线程同时访问同一资源时可能会出现错误。Java提供了synchronized关键字来同步多个线程访问同一资源的行为。下面是一个使用synchronized关键字实现线程同步的例子:
public class Counter {
private int count;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
public class MyThread extends Thread {
private Counter counter;
public MyThread(Counter counter) {
this.counter = counter;
}
public void run() {
for (int i = 0; i< 10000; i++) {
counter.increment();
}
}
}
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
MyThread thread1 = new MyThread(counter);
MyThread thread2 = new MyThread(counter);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException ex) {}
System.out.println(counter.getCount());
}
}结论
Java中的多线程机制可以使程序并行执行多个任务,提高程序效率。同时,多线程涉及到竞争条件,需要进行同步,而线程中断可以让一个正在执行的线程停止执行。