java多线程练习题

  • 格式:docx
  • 大小:37.41 KB
  • 文档页数:6

java多线程练习题

在Java编程中,多线程是一个非常重要的概念,它允许程序同时执行多个任务,提高程序的效率和响应性。以下是一些Java多线程的练习题,可以帮助你更好地理解和掌握多线程的概念和应用。

# 练习题1:线程的创建和启动

编写一个Java程序,创建一个继承自Thread类的子类,并重写run方法。然后创建该子类的实例,并启动线程。

```java

class MyThread extends Thread {

public void run() {

System.out.println("线程启动了!");

}

}

public class Main {

public static void main(String[] args) {

MyThread thread = new MyThread();

thread.start();

}

}

```

# 练习题2:线程的同步

编写一个Java程序,模拟两个线程交替打印1到10的数字。使用同步方法或同步代码块来保证线程安全。

```java

class Counter {

private int count = 1;

public synchronized void increment() {

System.out.println(Thread.currentThread().getName() +

"打印了:" + count);

count++;

}

}

public class Main {

public static void main(String[] args) {

Counter counter = new Counter();

Thread thread1 = new Thread(() -> {

for (int i = 0; i < 5; i++) {

counter.increment();

}

});

Thread thread2 = new Thread(() -> {

for (int i = 0; i < 5; i++) {

counter.increment();

}

});

thread1.start();

thread2.start();

}

}

```

# 练习题3:使用wait和notify

编写一个Java程序,模拟生产者和消费者问题。生产者在生产产品后使用notify通知消费者,消费者在消费产品后使用wait等待产品。

```java

class Product {

private int value;

public synchronized void setValue() {

value++;

System.out.println("生产了产品:" + value);

notify();

}

public synchronized void consume() {

while (value == 0) {

try {

wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println("消费了产品:" + value--);

}

}

public class Main {

public static void main(String[] args) {

Product product = new Product();

Thread producer = new Thread(() -> { for (int i = 0; i < 10; i++) {

product.setValue();

}

});

Thread consumer = new Thread(() -> {

for (int i = 0; i < 10; i++) {

product.consume();

}

});

producer.start();

consumer.start();

}

}

```

# 练习题4:线程的中断

编写一个Java程序,创建一个线程,该线程在执行一个无限循环。然后编写代码来中断这个线程。

```java

class InfiniteLoop extends Thread {

public void run() {

while (!Thread.currentThread().isInterrupted()) {

System.out.println("线程正在运行!");

}

System.out.println("线程被中断了!");

}

}

public class Main {

public static void main(String[] args) throws

InterruptedException {

InfiniteLoop thread = new InfiniteLoop();

thread.start();

Thread.sleep(5000); // 让线程运行5秒

thread.interrupt(); // 中断线程

}

}

```

# 练习题5:线程池的使用

编写一个Java程序,使用Executor框架创建一个线程池,并提交多个任务到线程池中执行。

```java

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class Main {

public static void main(String[] args) {

ExecutorService executor =

Executors.newFixedThreadPool(5);

for (int i = 0; i < 10; i++) {

executor.submit(() -> {

System.out.println("任务" + (i + 1) + "由线程" + Thread.currentThread().getName() + "执行");

});

}

executor.shutdown();

} }

```

这些练习题覆盖了Java多线程编程的基础知识,包括线程的创建、同步、等待和通知机制、线程的中断以及线程池的使用。通过解决这些问题,你可以加深对Java多线程编程的理解,并提高解决实际问题的能力。