Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- public class Main {
- public static void main(String[] args) {
- new Main();
- }
- public Main() {
- new ThreadOne().start();
- }
- public class ThreadOne extends MyThread {
- public ThreadOne() {
- super("one");
- }
- @Override
- void startOtherThread() {
- new ThreadTwo().start();
- }
- }
- public class ThreadTwo extends MyThread {
- public ThreadTwo() {
- super("two");
- }
- @Override
- void startOtherThread() {
- new ThreadOne().start();
- }
- }
- abstract static class MyThread extends Thread {
- private static Random random = new Random();
- private String name;
- public MyThread(String name) {
- this.name = name;
- }
- @Override
- public void run() {
- while (!isInterrupted()) {
- System.out.println("Thread " + name + " is running!");
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- if (random.nextInt(3) == 0) {
- interrupt();
- System.out.println("Thread " + name + " was interrupted!");
- startOtherThread();
- }
- }
- }
- abstract void startOtherThread();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement