자바 다 중 스 레 드 연속 인쇄 알파벳 숫자 문제

2796 단어 자바
//2.두 개의 스 레 드 를 쓰 고 한 스 레 드 는 1-52 를 인쇄 하 며 다른 스 레 드 는 알파벳 A-Z 를 승낙 합 니 다.
//인쇄 순 서 는 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();
	}
	
}
}

좋은 웹페이지 즐겨찾기