当前位置:首页 > Java多线程题目及答案
3 编写2个线程,第一个线程,打印字母A-Z,第二个线程打印数字0-9,要求先打印完数字才能打印字母。
package 线程;
class Thread1 extends Thread{ public void run() {
for(int i = 0;i < 10;i++) { System.out.println(i); } } }
class Thread2 extends Thread{ public void run() { char zi = 'A';
for(int i = 0;i < 26;i++) { System.out.println(zi); zi++; } } }
public class Test3 {
public static void main(String[] args) { Thread1 t1 = new Thread1(); Thread2 t2 = new Thread2(); t1.start(); try {
t1.join();
} catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); }
t2.start(); } }
4有一个抽奖池,该抽奖池中存放了奖励的金额,该抽奖池用一个数组int[] arr = {10,5,20,50,100,200,500,800,2,80,300};
创建两个抽奖箱(线程)设置线程名称分别为“抽奖箱1”,“抽奖箱2”,随机从arr数组中获取奖项元素并打印在控制台上,格式如下: 抽奖箱1 又产生了一个 10 元大奖
抽奖箱2 又产生了一个 100 元大奖 //.....
package 线程;
public class Test4 {
public static void main(String[] args) { Jang j = new Jang();
Thread t3 = new Thread(j,\抽奖箱1\ Thread t4 = new Thread(j,\抽奖箱2\
t3.start(); t4.start(); } }
class Jang implements Runnable{
int[] arr = {10,5,20,50,100,200,500,800,2,80,300}; int count = arr.length;
boolean [] flag = new boolean[arr.length];
public void run() { while(true) {
synchronized (this) { if(count>0) {
//随机获取数组下标
int index = (int)(Math.random()*arr.length); //获取得到的数字
int get = arr[index];
//代表这张奖票已经抽过
if(flag[index]!= true) { flag[index] = true;
System.out.println(Thread.currentThread().getName()+\又产生了一个\元大奖!\ count--; } } } } } }
5 模拟多个人通过一个山洞。这个山洞每次只能通过一个人,每个人过山洞的时间为5秒,随机生成10个人,同时准备过山洞,要求显示每个人过山洞的过程,(姓名,准备进入,在洞中,出来了)具体参考运行结果。
下图是某次部分的运行结果,供参考
package 线程;
public class Test5 {
public static void main(String[] args) { dong d = new dong();
Thread thread1 = new Thread(d,\游客1号\ Thread thread2 = new Thread(d,\游客2号\ Thread thread3 = new Thread(d,\游客3号\ Thread thread4 = new Thread(d,\游客4号\ Thread thread5 = new Thread(d,\游客5号\ Thread thread6 = new Thread(d,\游客6号\ Thread thread7 = new Thread(d,\游客7号\ Thread thread8 = new Thread(d,\游客8号\ Thread thread9 = new Thread(d,\游客9号\ Thread thread10 = new Thread(d,\游客10号\
thread1.start(); thread2.start(); thread3.start(); thread4.start(); thread5.start(); thread6.start(); thread7.start(); thread8.start(); thread9.start(); thread10.start(); } }
class dong extends Thread{ public void run() {
synchronized (this) {
System.out.println(Thread.currentThread().getName()+\准备进入山洞\
System.out.println(Thread.currentThread().getName()+\正在通过山洞。。。\ try {
Thread.sleep(5000);
} catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); }
System.out.println(Thread.currentThread().getName()+\已经通过山洞\
System.out.println(); } } }
6 有10个窗口(W1, W2, W3……W10),同时对外开放售票,一共有票50张(T1,T2……T50)需要按顺序售出。
要求:输出每一张票的售出时间和售出窗口,不能出现票未售出或者被售出多次的情况。
package 线程;
public class Test6 {
public static void main(String[] args) { window w = new window();
Thread t1 = new Thread(w,\窗口1\ Thread t2 = new Thread(w,\窗口2\ Thread t3 = new Thread(w,\窗口3\
共分享92篇相关文档