题目
分析
可以参考Java线程生产者和消费者实例
代码如下
运行结果如下
本文链接:https://liuyanzhao.com/4481.html
借助同步机制、sleep()方法、join()方法,实现动画显示:
甲线程输出:1、3、5、7、9
乙线程输出:2、4、6、8、0
丙线程数出:a、b、c、d、e
main线程输出:线程开始、线程结束
最终输出结果为(注:这是唯一可能的结果)
线程开始:1-2-a## 3-4-b## 5-6-c## 7-8-d## 9-0-e## 线程结束
要求:每隔一秒输出一个字符。(借助sleep)
分析
可以参考Java线程生产者和消费者实例
代码如下
- package com.liuyanzhao;
- /*
- *
- * @author WellsLiu
- *
- */
- class Resource {
- int flag=1;
- }
- class Thread1 extends Thread {
- Resource res;
- public Thread1(Resource res) {
- this.res = res;
- }
- int i=0;
- char []c1 = {'1','3','5','7','9'};
- public void run() {
- synchronized (res) {
- while(i<5) {
- while(res.flag!=1) {
- try {
- res.wait();//t1
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.print(c1[i]);
- try {
- sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.print("-");
- try {
- sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- i++;
- res.notifyAll();
- res.flag=2;
- }
- }
- }
- }
- class Thread2 extends Thread {
- Resource res;
- public Thread2(Resource res) {
- this.res = res;
- }
- int i=0;
- char []c1 = {'2','4','6','8','0'};
- public void run() {
- synchronized (res) {
- while(i<5) {
- while(res.flag!=2) {
- try {
- res.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.print(c1[i]);
- try {
- sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.print("-");
- try {
- sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- i++;
- res.notifyAll();
- res.flag=3;
- }
- }
- }
- }
- class Thread3 extends Thread {
- Resource res;
- public Thread3(Resource res) {
- this.res = res;
- }
- int i=0;
- char []c1 = {'a','b','c','d','e'};
- public void run() {
- synchronized (res) {
- while(i<5) {
- while(res.flag!=3) {
- try {
- res.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.print(c1[i]);
- try {
- sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.print("#");
- try {
- sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.print("#");
- try {
- sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.print(" ");
- i++;
- res.notifyAll();
- res.flag=1;
- }
- }
- }
- }
- public class Test1 {
- public static void main(String[] args) throws InterruptedException {
- System.out.printf("线程开始: ");
- Resource res = new Resource();
- Thread1 t1 = new Thread1(res);
- Thread2 t2 = new Thread2(res);
- Thread3 t3 = new Thread3(res);
- t1.start();
- t2.start();
- t3.start();
- t1.join();
- t3.join();
- t2.join();
- System.out.print("线程结束");
- }
- }
运行结果如下
本文链接:https://liuyanzhao.com/4481.html
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏