Java语言程序设计(一)

发布于:2024-12-08T13:29:00.000000Z

学习人数:0

知识点:693

更新于:2024-12-08T13:29:09.000000Z

Java的特点

多线程

重要程度:8 分
<div> <h2>Java的特点 - 多线程</h2> <p><strong>1. 什么是多线程?</strong></p> <p>多线程是指在一个程序中同时运行多个线程,每个线程都是程序的一个执行路径。多线程使得程序能够同时执行多个任务,提高程序的执行效率。</p> <p><strong>2. Java中的多线程</strong></p> <p>在Java中,实现多线程有两种方式:</p> <ul> <li>继承Thread类</li> <li>实现Runnable接口</li> </ul> <p><strong>3. 继承Thread类实现多线程</strong></p> <p>创建一个类继承自Thread类,并重写run()方法。</p> <pre> <code> class MyThread extends Thread { public void run() { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + " : " + i); } } } public class Main { public static void main(String[] args) { MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); t1.start(); t2.start(); } } </code> </pre> <p><strong>4. 实现Runnable接口实现多线程</strong></p> <p>创建一个类实现Runnable接口,并实现run()方法。</p> <pre> <code> class MyRunnable implements Runnable { public void run() { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + " : " + i); } } } public class Main { public static void main(String[] args) { MyRunnable r1 = new MyRunnable(); Thread t1 = new Thread(r1); Thread t2 = new Thread(r1); t1.start(); t2.start(); } } </code> </pre> <p><strong>5. 线程同步</strong></p> <p>当多个线程访问同一个资源时,可能会发生冲突,这时需要使用synchronized关键字来保证线程同步。</p> <pre> <code> class Counter { private int count = 0; public synchronized void increment() { count++; } public synchronized int getCount() { return count; } } public class Main { public static void main(String[] args) { Counter counter = new Counter(); Thread t1 = new Thread(() -> { for (int i = 0; i < 1000; i++) { counter.increment(); } }); Thread t2 = new Thread(() -> { for (int i = 0; i < 1000; i++) { counter.increment(); } }); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Count: " + counter.getCount()); } } </code> </pre> </div>
上一条 下一条