package thread; public abstract class Counter { static int count = 0; }
package thread; public class ThreadC implements Runnable { @Override public void run() { for(int i=0;i<10;i++){ System.out.println('a'); Counter.count++; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
package thread; public class ThreadD implements Runnable { @Override public void run() { int lastCount = 0; while(Counter.count<10){ if(lastCount != Counter.count){ System.out.println(Counter.count); lastCount = Counter.count; } } } }
package thread; public class Test { public class Lock{ } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub test2(); } // public static void test1(){ // Test test = new Test(); // Lock lock = test.new Lock(); // Thread a = new Thread(new ThreadA(lock)); // Thread b = new Thread(new ThreadB(lock)); // a.start(); // b.start(); // } public static void test2(){ Thread c = new Thread(new ThreadC()); Thread d = new Thread(new ThreadD()); c.start(); d.start(); } }
代码不多,直接帖上。
完成的功能是:创建两个线程,一个每秒打印一个字符,另一个计数