1. 程式人生 > >多執行緒練習一

多執行緒練習一

package 多執行緒;

import java.util.Random;

public class Example1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Thread1 th = new Thread1();
		for(int i =0;i<10;i++)
		{
			th.run();
		}
	}

}

class Thread1 implements Runnable{

	public static String getRandomString(int length)
	{
		String firstName = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		String lastName="abcdefghigklmnopqrstuvwxyz";
		Random r = new Random();
		StringBuffer s = new StringBuffer();
		int n = r.nextInt(firstName.length());
		s.append(firstName.charAt(n));
		for(int i = 0;i<length;i++)
		{
			int num = r.nextInt(lastName.length());
			s.append(lastName.charAt(num));
		}
		return s.toString();
		
	}
	
	@Override
	public  synchronized void run() {
		// TODO Auto-generated method stub
		Random r = new Random();
		int name =r.nextInt(50);
		try {
			Thread.sleep(2000);
		} catch (Exception e) {
			// TODO: handle exception
		}
		System.out.println(Thread1.getRandomString(6)+"的人通過了山洞");
	}
	
}