怎么做单页竞价网站,英文seo公司,网站建设需要使用哪些设备,百度云资源搜索平台写两个线程#xff0c;其中一个线程打印1-52#xff0c;另一个线程打印A-Z#xff0c;打印顺序应该是12A34B56C......5152Z。 该习题需要用到多线程通信的知识。 思路分析#xff1a; 把打印数字的线程称为线程N#xff0c;打印字母的线程称为线程L. 1.线程N完成打印后其中一个线程打印1-52另一个线程打印A-Z打印顺序应该是12A34B56C......5152Z。 该习题需要用到多线程通信的知识。 思路分析 把打印数字的线程称为线程N打印字母的线程称为线程L. 1.线程N完成打印后需要等待通知线程L打印同理线程L打印后也需要等待并通知线程N打印 线程的通信可以利用Object的wait和notify方法。 2.两个线程在执行各自的打印方法的时候不应该被打断所以把打印方法设置成同步的方法。 3.两个线程何时停止打印当两个线程的打印方法都执行了26次的时候。 实现 1.PrintStr类用来完成打印拥有printNumber和printLetter两个同步方法 1 package pratise.multithreading;2 3 public class {4 5 private int flag0;6 private int beginIndex1;7 private int beginLetter65;8 9 private int nCount0;
10 private int lCount0;
11
12 public int getnCount()
13 {
14 return nCount;
15 }
16
17 public int getlCount()
18 {
19 return lCount;
20 }
21
22 public synchronized void printNumber()
23 {
24 try {
25 if(flag0)
26 {
27 nCount;
28 System.out.print(beginIndex);
29 System.out.print(beginIndex1);
30 beginIndex2;
31 //改标志位
32 flag;
33 //唤醒另一个线程
34 notify();
35 }else
36 {
37 wait();
38 }
39 } catch (InterruptedException e) {
40 e.printStackTrace();
41 }
42
43 }
44
45 public synchronized void printLetter()
46 {
47 try {
48 if(flag1)
49 {
50 lCount;
51 char letter(char)beginLetter;
52 System.out.print(String.valueOf(letter));
53 beginLetter;
54 flag--;
55 notify();
56 }else
57 {
58 wait();
59
60 }
61 } catch (InterruptedException e) {
62 // TODO Auto-generated catch block
63 e.printStackTrace();
64 }
65
66
67 }
68
69 } 2.两个线程类分别包含一个PrintStr对象 1 package pratise.multithreading;2 3 public class PrintNumberThread extends Thread {4 private PrintStr ps;5 public PrintNumberThread(PrintStr ps)6 {7 this.psps;8 }9
10 public void run()
11 {
12
13 while(ps.getnCount()26)
14 {
15 ps.printNumber();
16 }
17 }
18 } 1 package pratise.multithreading;2 3 public class PrintLetterThread extends Thread {4 private PrintStr ps;5 public PrintLetterThread(PrintStr ps)6 {7 this.psps;8 }9
10 public void run()
11 {
12 while(ps.getlCount()26)
13 {
14 ps.printLetter();
15 }
16 }
17 } 3.含有main方法的类用来启动线程。 1 package pratise.multithreading;2 3 public class PrintTest {4 5 public static void main(String[] args) {6 PrintStr psnew PrintStr();7 new PrintNumberThread(ps).start();8 new PrintLetterThread(ps).start();9 }
10
11 } 转载于:https://www.cnblogs.com/wsw-tcsygrwfqd/p/11333281.html