java多线程连续打印字母数字问题

Posted 心忘则忘

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java多线程连续打印字母数字问题相关的知识,希望对你有一定的参考价值。

//2.写两个线程,一个线程打印1-52,另一个线程答应字母A-Z。
//打印顺序为12A34B56C……5152Z。通过使用线程之间的通信协调关系。
//注:分别给两个对象构造一个对象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();
	
	



以上是关于java多线程连续打印字母数字问题的主要内容,如果未能解决你的问题,请参考以下文章

java多线程轮流打印数字字母案例代码

经典多线程问题-轮流打印字母和数字

一个java多线程面试题

Java 线程:如何一次使用两个线程打印字母和数字

java多线程编程之连续打印abc的几种解法

写两个线程,交替打印数字和字母,一个线程打印 1~26,另一个线程打印字母 A-Z