日期:2014-05-20 浏览次数:20752 次
public class Demo { public static void main(String args[]) { MyThread mt1 = new MyThread(); MyThread mt2 = new MyThread(); MyThread mt3 = new MyThread(); new Thread(mt1, "线程1").start(); new Thread(mt2, "线程2").start(); new Thread(mt3, "线程2").start(); } } class MyThread implements Runnable { private static Integer id = 0; public void run() { for(int i = 0; i < 30; i ++) { synchronized(id) { id++; System.out.println(Thread.currentThread().getName() + " id = " + id); } } } }
public class Demo5 { public static void main(String args[]) { MyThread5 mt = new MyThread5(); new Thread(mt, "线程1").start(); new Thread(mt, "线程2").start(); } } class MyThread5 implements Runnable { private static Integer id = 0; public void run() { synchronized(id) { id++; String name = Thread.currentThread().getName(); if(name.equals("线程1")) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(name + " id = " + id); } } }
public class Demo5 { public static void main(String args[]) { MyThread5 mt = new MyThread5(); new Thread(mt, "线程1").start(); new Thread(mt, "线程2").start(); } } class MyThread5 implements Runnable { private static StringBuilder id = new StringBuilder("0"); public void run() { synchronized(id) { int t = Integer.parseInt(id.toString()); t++; id.delete(0, id.length()); id.append(t); String name = Thread.currentThread().getName(); if(name.equals("线程1")) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(name + " id = " + id); } } }