public class Test95 { public static void main(String[] args) { Window95 w=new Window95(); Thread t1=new Thread(w); Thread t2=new Thread(w); Thread t3=new Thread(w); //为线程命名 t1.setName("线程1"); t2.setName("线程2"); t3.setName("线程3"); //启动线程 t1.start(); t2.start(); t3.start(); } }
import java.util.concurrent.locks.ReentrantLock; public class Window95 implements Runnable{ ReentrantLock lock=new ReentrantLock(); private int age=500; @Override public void run() { while (true){ try { lock.lock(); if (age<550){ try { Thread.sleep(35); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+":"+age); try { Thread.sleep(25); } catch (InterruptedException e) { e.printStackTrace(); } age++; }else { break; } }finally { lock.unlock(); } } } }