java编程线程题1、模拟3个老师同时给10个小朋友发礼品,每个老师相当于一个线程。 2、编写一个程序,创建两个线程,要求分别输出26个字母。在输出结果时,要显示是哪个线程输出的字母。 3、编写一个程序,使用Runnable接口的方式创建两个线程,分别输出从0到10的数,每个线程之间延迟500毫秒,要求输出的结果如下所示: 线程一 : 0,1,2,3,4,5,6,7,8,9,10 线程二 : 0,1,2,3,4,5,6,7,8,9,10
时间: 2023-08-21 08:02:39 浏览: 87
java编写的一个多线程程序,模拟银行排队.zip
1. Java编程线程题-模拟老师发礼品:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TeacherGift {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
for (int i = 1; i <= 3; i++) {
executorService.execute(new Teacher(i));
}
executorService.shutdown();
}
}
class Teacher implements Runnable {
private final int teacherId;
public Teacher(int teacherId) {
this.teacherId = teacherId;
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Teacher " + teacherId + " gives gift to student " + i);
}
}
}
```
2. Java编程线程题-输出26个字母:
```java
public class Alphabet {
public static void main(String[] args) {
Thread t1 = new Thread(new PrintAlphabet("Thread 1"));
Thread t2 = new Thread(new PrintAlphabet("Thread 2"));
t1.start();
t2.start();
}
}
class PrintAlphabet implements Runnable {
private final String threadName;
public PrintAlphabet(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
for (char c = 'A'; c <= 'Z'; c++) {
System.out.println(threadName + " prints " + c);
}
}
}
```
3. Java编程线程题-延迟输出:
```java
public class DelayOutput {
public static void main(String[] args) {
Thread t1 = new Thread(new PrintNumber("线程一"));
Thread t2 = new Thread(new PrintNumber("线程二"));
t1.start();
t2.start();
}
}
class PrintNumber implements Runnable {
private final String threadName;
public PrintNumber(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
for (int i = 0; i <= 10; i++) {
System.out.print(threadName + " : " + i + ",");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println();
}
}
```
阅读全文