동시에 실행하는게 비동기적

차례로 실행하는게 동기적

//스레드 2개가 섞여서 나옴
package ex16;

class MyRunnable implements Runnable {
    String myName;

    public MyRunnable(String myName) {
        this.myName = myName;
    }
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.print(myName + i + " ");
        }
    }
}

public class TestThread {
    public static void main(String[] args) {
        Thread t1 = new Thread(new MyRunnable("A"));
        Thread t2 = new Thread(new MyRunnable("B"));
        t1.start();
        t2.start();
    }
}

Untitled

그래픽 버전 카운터 만들기

package ex16;

import javax.swing.*;
import java.awt.*;

public class CountDownTest extends JFrame {
    private JLabel label;
    private int i;
    class MyThread extends Thread {
        public void run() {
            while (true) {
                try {
                    i++;
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                label.setText(i + "");
            }
        }
    }

    public CountDownTest() {
        setTitle("카운트다운");
        setSize(400, 150);
        label = new JLabel("Start");
        label.setFont(new Font("Start", Font.BOLD, 100));
        add(label);
        setVisible(true);
        (new MyThread()).start(); // 스레드를 시작
    }

    public static void main(String[] args) {
        CountDownTest t = new CountDownTest();
    }
}

Untitled

Untitled

자동차 경주 게임

package ex16;

import javax.swing.*;

public class CarGame extends JFrame {
    class MyThread extends Thread {
        private JLabel label;
        private int x, y;

        public MyThread(String fname, int x, int y) {
            this.x = x;
            this.y = y;
            label = new JLabel();
            label.setIcon(new ImageIcon(fname));
            label.setBounds(x, y, 100, 100);
            add(label);
        }

        public void run() {
            for (int i = 0; i < 200; i++) {
                x += 10 * Math.random();
                label.setBounds(x, y, 100, 100);
                repaint();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public CarGame() {
        setTitle("CarRace");
        setSize(600, 340);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(null);
        (new MyThread("D:\\\\01.png", 100, 0)).start();
        (new MyThread("D:\\\\02.png", 100, 100)).start();
        (new MyThread("D:\\\\03.png", 100, 200)).start();
        setVisible(true);
    }

    public static void main(String[] args) {
        CarGame c = new CarGame();
    }
}

Untitled