admin 管理员组

文章数量: 1184232


2024年3月13日发(作者:数据库原理及应用第三版杨爱民)

java多线程练习题

在Java中,多线程是一种重要的编程概念,它允许程序同时执行多

个任务。为了帮助大家更好地理解和掌握多线程编程,本文将介绍一

些常见的Java多线程练习题,帮助读者进行实践和巩固知识。

1. 编写一个Java程序,创建两个线程,一个线程打印 1-50 的奇数,

另一个线程打印 1-50 的偶数。

```java

public class OddEvenPrinter implements Runnable {

private int max;

private static int number = 1;

private boolean isOddNumberThread;

public OddEvenPrinter(int max, boolean isOddNumberThread) {

= max;

umberThread = isOddNumberThread;

}

@Override

public void run() {

while (number <= max) {

synchronized () {

if ((number % 2 == 0 && !isOddNumberThread)

|| (number % 2 != 0 && isOddNumberThread)) {

n(tThread().getName() + ": "

+ number);

number++;

();

} else {

try {

();

} catch (InterruptedException e) {

tackTrace();

}

}

}

}

}

public static void main(String[] args) {

int max = 50;

Thread oddThread = new Thread(new OddEvenPrinter(max, true),

"Odd");

Thread evenThread = new Thread(new OddEvenPrinter(max, false),

"Even");

();

();

}

}

```

2. 编写一个Java程序,模拟银行账户的存取款操作。创建一个初始

金额为100的账户,开启两个线程分别模拟存款和取款操作,要求存

款线程每次存入10元,取款线程每次取出20元,直到账户金额小于

等于0时停止。

```java

public class BankAccount {

private int balance;

public BankAccount(int initBalance) {

e = initBalance;

}

public synchronized void deposit(int amount) {

balance += amount;


本文标签: 线程 程序 账户 操作 帮助