【发布时间】:2021-04-26 12:52:54
【问题描述】:
我使用线程同步方法打印 ASCII 码及其值,如下例所示。
例如:-
一个
65
乙
66
C
67
.
.
.
.
Z
90
但输出是这样的。
以下是两个线程。
线程 1
public class PrintingASCII extends Thread{
private Object ob;
public PrintingASCII(Object ob) {
this.ob = ob;
}
public void run() {
synchronized(ob) {
for(int i=65;i<=90;i++) {
System.out.println(i);
}
}
}
}
线程 2
public class PrintingCapital extends Thread{
private Object ob;
public PrintingCapital(Object ob) {
this.ob = ob;
}
public void run() {
synchronized(ob) {
for(char i='A';i<='Z';i++) {
System.out.println(i);
}
}
}
}
主要
public class Main {
public static void main(String[] args) {
Object ob = new Object();
System.out.println("PLAAA");
PrintingASCII thread1 = new PrintingASCII(ob);
PrintingCapital thread2 = new PrintingCapital(ob);
thread1.start();
thread2.start();
}
}
在不改变main方法的情况下我能做什么?
【问题讨论】:
-
在
System.out.println和ob.notify()之一之前添加ob.wait() -
并将
syncronized放在等待/通知调用周围的循环中,例如for(char i='A';i<='Z';i++) {synchronized(ob) {ob.wait();} System.out.println(i);}
标签: java multithreading oop synchronization synchronized