Java多线程交替打印模板
Java多线程交替打印模板
- 可调整循环打印次数
- 可调整打印内容
- 可调整多少个线程循环打印
1、交替打印数字
/*** 交替打印数字* 以 1-100 为例*/
public class CyclePrinterNumbers {static class MyPrinter {int flag = 1;public void print(int printFlag, int nextFlag) {//调整1:循环次数j 无限打印时可使用while(true)for (int j = 0; j < 10; j++) {// }
// while (true) {synchronized (this) {while (flag != printFlag) {try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}//调整2:打印内容for (int i = 1; i <= 100; i++) {System.out.print(i + " ");if (i == 100) {System.out.println(Thread.currentThread().getName() + " done");}}this.notifyAll();flag = nextFlag;}}}}public static void main(String[] args) {MyPrinter myPrinter = new MyPrinter();//调整3:创建i个线程for (int i = 1; i <= 3; i++) {final int flag = i; //打印线程final int nextFlag;if (flag == 3) {nextFlag = 1;} else {nextFlag = flag + 1;}Thread thread = new Thread(new Runnable() {@Overridepublic void run() {myPrinter.print(flag, nextFlag);}});thread.setName("thread " + i);thread.start();}}
}
2、交替打印字符
/*** 交替打印 字符* 以 ++ -- ** // ++ -- ** // 为例*/
public class CyclePrinterString {static class MyPrinter {int flag = 1;public void print(String str, int printFlag, int nextFlag) {
// for (int j = 0; j < 10; j++) {
// }while (true) {synchronized (this) {while (flag != printFlag) {try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.print(str + " ");
// if (flag == 4) {
// System.out.println();
// }this.notifyAll();flag = nextFlag;}}}}public static void main(String[] args) {MyPrinter myPrinter = new MyPrinter();//创建3个线程for (int i = 1; i <= 4; i++) {final int flag = i; //打印线程final int nextFlag;if (flag == 4) {nextFlag = 1;} else {nextFlag = flag + 1;}final String str;switch (i) {case 1:str = "++";break;case 2:str = "--";break;case 3:str = "**";break;default:str = "//";}Thread thread = new Thread(new Runnable() {@Overridepublic void run() {myPrinter.print(str, flag, nextFlag);}});thread.setName("thread " + i);thread.start();}}
}
部分笔试题实例
该部分面试题/笔试题实例来自 @ 几到多线程笔试题,有时间练练。
例如如下面试题,以上模板可以解决面试题3~5
-
第三题(某培训机构的练习题):
子线程循环 10 次,接着主线程循环 100 次,接着又回到子线程循环 10 次,接着再回到主线程又循环 100 次,如此循环50次,试写出代码。 -
第四题(迅雷笔试题):
编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。 -
第五题(Google面试题)
有四个线程1、2、3、4。线程1的功能就是输出1,线程2的功能就是输出2,以此类推…现在有四个文件ABCD。初始都为空。现要让四个文件呈如下格式:
A:1 2 3 4 1 2…
B:2 3 4 1 2 3…
C:3 4 1 2 3 4…
D:4 1 2 3 4 1…
问题6 7 解法见本人下面两篇文章
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
