マルチスレッドの簡単な例

1551 ワード

一、例
public static class TicketWindowX implements Runnable {
        int max_value = 0;

        private Object lock = new Object();

        @Override
        public void run() {
            while (true) {
                if (max_value > 5) {
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + ":" + max_value++);

            }
        }
    }
    
    
 :
Thread-0:0
Thread-2:1
Thread-1:2
Thread-0:3
Thread-2:4
Thread-1:5
Thread-0:6
Thread-2:7

二、例
    
public static class TicketWindowX implements Runnable {
        int max_value = 0;
        
        // 
        private Object lock = new Object();

        @Override
        public void run() {
            while (true) {
                // 
                synchronized (lock) {
                    if (max_value > 5) {
                        break;
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ":" + max_value++);
                }
            }
        }
    }
    
 :
Thread-0:0
Thread-0:1
Thread-1:2
Thread-1:3
Thread-1:4
Thread-2:5