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
| package com.example.demo;
public class DemoApplication {
public static void main(String[] args) { Thread thread1 = new Worker("A", 0); Thread thread2 = new Worker("B", 1); Thread thread3 = new Worker("C", 2); thread1.start(); thread2.start(); thread3.start(); }
static class Worker extends Thread { static volatile int n = 0; int order = 0;
Worker(String name, int order) { super(name); this.order = order; }
@Override public void run() { while (true) { if (order == n) { if (n == 2) { System.out.println(getName()); n = 0; } else { System.out.print(getName()); n++; } } } } } }
|