日期:2014-05-20 浏览次数:20829 次
String s=""; LoopThread lt01=new LoopThread(al1,al2,al3,al4,al5,al6,al7,al8,al9,al10,bomal2,al11,s ); lt01.start(); LoopThread lt02=new LoopThread(al2,al3,al4,al5,al6,al7,al8,al9,al10,al1,bomal2,al11,s ); lt02.start(); LoopThread lt03=new LoopThread(al3,al4,al5,al6,al7,al8,al9,al10,al1,al2,bomal2,al11,s ); lt03.start(); LoopThread lt04=new LoopThread(al4,al5,al6,al7,al8,al9,al10,al1,al2,al3,bomal2,al11,s ); lt04.start(); LoopThread lt05=new LoopThread(al5,al6,al7,al8,al9,al10,al1,al2,al3,al4,bomal2,al11,s ); lt05.start(); LoopThread lt06=new LoopThread(al6,al7,al8,al9,al10,al1,al2,al3,al4,al5,bomal2,al11,s ); lt06.start(); LoopThread lt07=new LoopThread(al7,al8,al9,al10,al1,al2,al3,al4,al5,al6,bomal2,al11,s ); lt07.start(); LoopThread lt08=new LoopThread(al8,al9,al10,al1,al2,al3,al4,al5,al6,al7,bomal2,al11,s ); lt08.start(); LoopThread lt09=new LoopThread(al9,al10,al1,al2,al3,al4,al5,al6,al7,al8,bomal2,al11,s ); lt09.start(); LoopThread lt10=new LoopThread(al10,al1,al2,al3,al4,al5,al6,al7,al8,al9,bomal2,al11,s ); lt10.start();
public void run() { s.wait(); ... s.notify(); }
------解决方案--------------------
不好意思,原先说的方法是错的,wait()和notify()是用于同步的,不是用于互斥的
还是用synchronized方法好了
public class Test { public static void main(String[] args) { StringBuilder s = new StringBuilder(); Object lock = new Object(); for (int i = 0; i < 10; i++) { new TestThread(i, s, lock).start(); } } } class TestThread extends Thread { private int i; //线程编号 private StringBuilder s; //要处理的字符串 private Object lock; //互斥的工具 public TestThread(int i, StringBuilder s, Object lock) { this.i = i; this.s = s; this.lock = lock; } public void run() { while (true) { synchronized (lock) { s.append(i); //将自己的编号添加到字符串中 System.out.println(s); //打印这个字符串被哪些线程调用过 } try { Thread.sleep(1000); //这里停一秒为了便于观察结果 } catch (InterruptedException e) { e.printStackTrace(); } } } }
------解决方案--------------------