1. Use Java to implement two threads to print numbers and letters alternately. The printed results are as follows: 1 2 A 3 4 B ...... Y 51 52 Z
public class TestThread { public static TestThread mHandler=new TestThread(); public static TestThread getHander(){ return mHandler; } public TestThread() { // TODO Auto-generated constructor stub } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub TestThread t = new TestThread(); ThreadA threadA = t.new ThreadA(); ThreadB threadB = t.new ThreadB(); threadA.start(); threadB.start(); } class ThreadA extends Thread{ private int num = 1; @Override public void run() { // TODO Auto-generated method stub super.run(); while(num<53){ synchronized(TestThread.this){ //synchronized(TestThread.getHander()){ System.out.print(num+" "+(num+1)+" "); num+=2; TestThread.this.notify(); if (num < 52){ try { TestThread.this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } } class ThreadB extends Thread{ private char ch = 'A'; @Override public void run() { // TODO Auto-generated method stub super.run(); while(ch<='Z'){ synchronized(TestThread.this){ //synchronized(TestThread.getHander()){ System.out.print(ch+" "); ch++; TestThread.this.notify(); try { TestThread.this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }}
2. Place 100 to one hundred random natural numbers into array. Java is used to obtain the largest number of duplicates and print them out.
Random ran = new Random(); int [] a=new int[100]; int [] b=new int[100]; for(int i=0;i<100;i++){ a[i]=Math.abs(ran.nextInt()%100); System.out.print(a[i]+","); } System.out.println("----"); for(int i=0;i<100;i++){ b[a[i]]++; } for(int i=0;i<100;i++){ System.out.print(b[i]+","); } System.out.println("----"); int k=b[0],max=0; for(int i=0;i<100;i++){ if(b[i]>=k){ k=b[i]; max=i; System.out.println(max+"----"+k); } } System.out.println(max+"----"+k);