package Thread; /** * * @author Administrator *创建ABC三条线程 保证A线程 打印 我 B线程 打印 爱 C线程 打印 你 循环10次 */ public class DoSomeTest { public static void main(String[] args) throws InterruptedException { Object a = new Object(); Object b = new Object(); Object c = new Object(); Thread t1 =new Thread(new DoSome("我",c,a)); Thread t2 =new Thread(new DoSome("爱",a,b)); Thread t3 =new Thread(new DoSome("你",b,c)); t1.start(); Thread.sleep(1000); t2.start(); Thread.sleep(1000); t3.start(); } }
package Thread; /** * 控制线程打字 * */ public class DoSome implements Runnable { //三个变量 三条线程之间切换执行 一把锁是不够的 需要两把锁 对象有锁的定义 Object对象 private String word;//线程要打印的字 private Object prev;//当前线程的上一个线程要持有的锁 private Object current;//当前线程所要持有的锁 @Override public void run() { for(int i = 0;i<10;i++){ synchronized(prev){ synchronized(current){ System.out.println(word); current.notify(); } try { prev.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } //打印字的操作 public DoSome(String word,Object prev,Object current){ this.word = word; this.prev = prev; this.current=current; } }
原文地址:https://www.cnblogs.com/ls1783047205/p/9751048.html
时间: 2024-11-15 22:23:53