자바 다 중 스 레 드 연속 인쇄 알파벳 숫자 문제
2796 단어 자바
//인쇄 순 서 는 12A34B56C...5152 Z 입 니 다.스 레 드 간 의 통신 을 통 해 관 계 를 조율 하 다.
//주:각각 두 대상 에 게 하나의 대상 o 를 만들어 준다.
//숫자 는 두 글자 나 알파벳 을 인쇄 할 때마다 o.wait()를 실행 합 니 다.o.wait()전에 o.notify()를 쓰 는 것 을 잊 지 마 세 요.
package homework2;
import com.sun.swing.internal.plaf.synth.resources.synth;
public class Test2 {
public static void main(String[] args) {
Object object = new Object();
shuzi shuzi = new shuzi(object);
zimu zimu = new zimu(object);
Thread t = new Thread(shuzi);
Thread t1 = new Thread(zimu);
t.start();//
t1.start();
}
}
class shuzi implements Runnable{
private Object object;
//
public shuzi(Object object) {
this.object = object;
}
public void run() {
synchronized (object) {//
for(int i=1;i<53;i++){
System.out.print(i);
if(i%2==0){
object.notifyAll();//
try {
object.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
class zimu implements Runnable{
private Object object;
public zimu(Object object) {
this.object = object;
}
public void run() {
synchronized (object) {
for(int j=65;j<91;j++){
char c = (char)j;
System.out.print(c);
object.notifyAll();
try {
object.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
방법 2:
public class Test {
public static void main(String[] args) {
O o = new O();
A a = new A(o);
B b = new B(o);
Thread t = new Thread(a);
Thread t1 = new Thread(b);
t.start();//
t1.start();
}
}
class O{
boolean flag = false;//
public synchronized void set() throws InterruptedException{
for(int i=1;i<52;i++){
if(this.flag == true){
this.wait();
}
if(i%2==0){
this.flag=true;
this.notifyAll();
}
System.out.print(i);
}
}
public synchronized void get() throws InterruptedException{
for(int j =65;j<91;j++){
if(this.flag == false){
this.wait();
}
char c = (char)j;
System.out.print(c);
this.flag = false;
this.notify();
}
}
}
class A implements Runnable{
O o = new O();
public A(O o) {
super();
this.o = o;
}
public void run() {
try {
o.set();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class B implements Runnable{
O o = new O();
public B(O o) {
super();
this.o = o;
}
public void run() {
try {
o.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.