1 import java.util.Random;
2
3 public class 多线程 {
4
5 public static Object lock = new Object();
6
7 public static void randomString() {
8 String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
9 Random random = new Random();
10 StringBuffer sb = new StringBuffer();
11 for (int i = 0; i < 4; i++) {
12 int number = random.nextInt(62);
13 sb.append(str.charAt(number));
14 }
15 System.out.print(sb);
16 }
17
18 public static void main(String[] args) {
19
20 new Thread(new myTh1()).start();
21 new Thread(new myTh2()).start();
22
23 }
24
25 }
26
27 class myTh1 extends Thread {
28 @Override
29 public void run() {
30 while (true) {
31
32 try {
33 synchronized (多线程.lock) {
34 多线程.randomString();
35 System.out.print("------"+Thread.currentThread().getName());
36 System.out.println();
37 }
38 sleep(1000);
39 } catch (InterruptedException e) {
40 e.printStackTrace();
41 }
42 }
43 }
44 }
45
46 class myTh2 extends Thread {
47 @Override
48 public void run() {
49 while (true) {
50 try {
51 synchronized (多线程.lock) {
52 多线程.randomString();
53 System.out.print("------"+Thread.currentThread().getName());
54 System.out.println();
55 }
56 sleep(1000);
57 } catch (InterruptedException e) {
58 e.printStackTrace();
59 }
60 }
61 }
62 }