 java实现两个线程交替打印0~100
java实现两个线程交替打印0~100
  public class jk {
         static volatile int num=0;
         static Object lock=new Object();
   public static void main(String[] args) {
       Runnable task1 = new Task1();
       Runnable task2 = new Task2();
       ExecutorService executorService = Executors.newFixedThreadPool(2);
       executorService.execute(task1);
       executorService.execute(task2);
       System.out.println("oo");
   }
 static    class Task1 implements Runnable{
       @Override
       public void run() {
           while (num<100){
               synchronized (lock){
                   if(num%2 == 0){
                       try {
                           lock.wait();
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                   }
                   System.out.println(Thread.currentThread().getName()+":"+ num++);
                   lock.notifyAll();
               }
           }
       }
   }
 static   class Task2 implements Runnable{
       @Override
       public void run() {
           while (num<100){
               synchronized (lock){
                   if(num%2 != 0){
                       try {
                           lock.wait();
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                   }
                   System.out.println(Thread.currentThread().getName()+":"+ num++);
                   lock.notifyAll();
               }
           }
       }
   }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
上次更新: 2024/08/09, 16:07:34
