package test; public class testThread { public static void main(String[] args) { Example example = new Example(); Example example2 = new Example(); Thread1 thread1 = new Thread1(example); Thread1 thread2 = new Thread1(example2); thread1.start(); thread2.start(); // Example example = new Example(); // Thread2 thread1 = new Thread2(example); // Thread2 thread2 = new Thread2(example); // thread1.start(); // thread2.start(); } } class Example { public void execute() { for (int i = 0; i < 10; ++i) { try { Thread.sleep((long) Math.random() * 1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Hello: " + i); } } public synchronized void execute2() { for (int i = 0; i < 10; ++i) { try { Thread.sleep((long) Math.random() * 1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("World: " + i); } } } class Thread1 extends Thread { private Example example; public Thread1(Example example) { this.example = example; } @Override public void run() { example.execute(); } } class Thread2 extends Thread { private Example example; public Thread2(Example example) { this.example = example; } @Override public void run() { example.execute2(); } }
http://www.2cto.com/kf/201408/322243.html
http://www.mamicode.com/info-detail-517008.html
http://www.cnblogs.com/rollenholt/archive/2011/08/28/2156357.html