Thread练习
来源:互联网 发布:广州数控980tdc编程 编辑:程序博客网 时间:2024/05/19 01:13
题目:现有三个线程,分别用于打印10次A,B,C,现在要求通过代码控制,实现线程按照先后顺序打印出ABCABCABCABCABCABCABCABCABCABC
我写的代码如下:
package com.example.testabc;public class TChar {private char c;public TChar(char c){this.c = c;}public char getC() {return c;}public void setC(char c) {this.c = c;}}
package com.example.testabc;public class PrintA implements Runnable{private TChar currentChar;public PrintA(TChar tchar){this.currentChar = tchar;}private void printChar(){synchronized(currentChar){while(currentChar.getC() != 'C'){try {currentChar.wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.printf("%c", 'A');currentChar.setC('A');currentChar.notifyAll();}}@Overridepublic void run() {for(int i=0; i<10; i++){printChar();}}}
package com.example.testabc;public class PrintB implements Runnable{private TChar currentChar;public PrintB(TChar tchar){this.currentChar = tchar;}private void printChar(){synchronized(currentChar){while(currentChar.getC() != 'A'){try {currentChar.wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.printf("%c", 'B');currentChar.setC('B');currentChar.notifyAll();}}@Overridepublic void run() {for(int i=0; i<10; i++){printChar();}}}
package com.example.testabc;public class PrintC implements Runnable{private TChar currentChar;public PrintC(TChar tchar){this.currentChar = tchar;}private void printChar(){synchronized(currentChar){while(currentChar.getC() != 'B'){try {currentChar.wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.printf("%c", 'C');currentChar.setC('C');currentChar.notifyAll();}}@Overridepublic void run() {for(int i=0; i<10; i++){printChar();}}}
package com.example.testabc;public class TestABC{public static void main(String[] args){TChar cchar = new TChar('C');PrintA pa = new PrintA(cchar);PrintB pb = new PrintB(cchar);PrintC pc = new PrintC(cchar);Thread threadA = new Thread(pa);Thread threadB = new Thread(pb);Thread threadC = new Thread(pc);threadA.start();threadB.start();threadC.start();}}
写得比较繁琐,希望大家可以给出自己的答案,一起分享。
0 0
- Thread练习
- boost库之thread练习
- Thread
- thread
- Thread
- Thread
- thread
- thread
- Thread
- Thread
- Thread
- Thread
- Thread
- Thread
- Thread
- Thread
- Thread
- Thread
- 图片压缩
- java 应用程序代理设置
- 在决赛中林丹爆冷输给了印度小将斯里坎斯
- Service初识
- 第13周项目1逆序输出、加倍后输出元素
- Thread练习
- Android Studio安装及主题字体配置
- 第十三周 项目一:数组大折腾(1.3)
- tomcat热部署
- LeetCode——Unique Paths II
- 第十三周项目一(1):输出数
- 虚函数必须实现吗?
- 第13周项目1-数组大折腾(1)
- 记录nginx+tomcat+memcached+msm负载均衡,session共享