public class ExampleRunnable implements Runnable{ private volatile int j; @Override public void run() { for (j = 0; j < 10; j+=2){ System.out.println("j = " + j); } } }
Demo 一下,看看執行結果:
public class ThreadDemo { public static void main(String[] args){ ExampleRunnable er1 = new ExampleRunnable(); Thread t1 = new Thread(er1); Thread t2 = new Thread(er1); Thread t3 = new Thread(er1); t1.start(); t2.start(); t3.start(); } }
syhchronized 範例: