Java Multithreading Example: Counter and SleepyCounter Threads
import java.util.Random;
class Counter implements Runnable { private static int count = 0;
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println('Counter: ' + count++);
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class SleepyCounter implements Runnable { private static int count = 0;
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println('SleepyCounter: ' + count++);
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class CounterApp { public static void main(String[] args) { Thread counterThread = new Thread(new Counter()); Thread sleepyCounterThread = new Thread(new SleepyCounter());
counterThread.start();
sleepyCounterThread.start();
}
}
原文地址: https://www.cveoy.top/t/topic/pjfT 著作权归作者所有。请勿转载和采集!