[英]How Can I print like below using thread synchronization method?
I have used thread Synchronization method to print ASCII code and its value like below example.我已经使用线程同步方法来打印 ASCII 代码及其值,如下例所示。
Ex:-前任:-
A一个
65 65
B乙
66 66
C C
67 67
. .
. .
. .
. .
Z Z
90 90
But the output is this.但是output就是这个。
Following are the two threads.以下是两个线程。
Thread 1线程 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);
}
}
}
}
Thread 2线程 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);
}
}
}
}
Main主要的
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();
}
}
What can I do for it without changing main method?在不改变主要方法的情况下我能做些什么?
This can be solved using two Object monitor.这可以使用两个 Object 监视器来解决。
So the two threads prints their values alternatively to achieve the required result.因此,两个线程交替打印它们的值以达到所需的结果。
I used String.class as second object monitor since the main is not allowed to be changed.我使用 String.class 作为第二个 object 监视器,因为不允许更改主监视器。 You can use any other object as monitor if you can access the main method.如果您可以访问 main 方法,您可以使用任何其他 object 作为监视器。
class PrintingASCII extends Thread {
private Object ob1;
private Object ob2;
public PrintingASCII(Object ob1) {
this.ob1 = ob1;
}
public void run() {
try {
for (int i = 65; i <= 90; i++) {
synchronized(ob1) {ob1.wait();}
System.out.println(i);
synchronized(String.class) {String.class.notify();}
}
}catch (Exception e) {
System.out.println("Exc : "+e);
}
}
}
class PrintingCapital extends Thread {
private Object ob1;
private Object ob2;
public PrintingCapital(Object ob1) {
this.ob1 = ob1;
}
public void run() {
try {
for (char i = 'A'; i <= 'Z'; i++) {
System.out.println(i);
synchronized(ob1) {ob1.notify();}
synchronized(String.class) {String.class.wait();}
}
}catch (Exception e) {
System.out.println("Exc : "+e);
}
}
}
public class Main {
public static void main(String[] args) {
Object ob1 = new Object();
PrintingASCII thread1 = new PrintingASCII(ob1);
PrintingCapital thread2 = new PrintingCapital(ob1);
thread1.start();
thread2.start();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.