标签:java
public class DemoThread { public static void main(String[] args) { ThreadTest runnable = new ThreadTest(); //声明一个Runnable子类对象 new Thread(runnable).start(); //创建四个线程,它们使用的是同一资源 new Thread(runnable).start(); new Thread(runnable).start(); new Thread(runnable).start(); } } //实现一个Runnable子类 public class ThreadTest implements Runnable { int tickets=100; String str = new String(); //定义一个锁旗标 public void run() { while(true) { synchronized(str) { if(tickets>0) { try { Thread.sleep(1000); } catch(Exception e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+" is saling tickets"+tickets--); } } } } }
public class DemoThread { public static void main(String[] args) { ThreadTest runnable = new ThreadTest(); //声明一个Runnable子类对象 new Thread(runnable).start(); //创建四个线程,它们使用的是同一资源 new Thread(runnable).start(); new Thread(runnable).start(); new Thread(runnable).start(); } }
public class ThreadTest implements Runnable { int tickets=100; public void run() { while(true) { sale(); } } public synchronized void sale() { if(tickets>0) { try { Thread.sleep(1000); } catch(Exception e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+" is saling tickets"+tickets--); } } }
public class A { synchronized void foo(B b) { String name = Thread.currentThread().getName(); //获取当前线程的名称 System.out.println(name+"enter A.foo"); try { Thread.sleep(100); } catch(Exception e) { e.printStackTrace(); } System.out.println(name+" is trying to call b.last"); b.last(); } synchronized void last() { System.out.println("inside A.last"); } }
public class B { synchronized void bar(A a) { String name = Thread.currentThread().getName(); //获取当前线程的名称 System.out.println(name+"enter B.bar"); try { Thread.sleep(100); } catch(Exception e) { e.printStackTrace(); } System.out.println(name+" is trying to call b.last"); a.last(); } synchronized void last() { System.out.println("inside B.last"); } }
public class BlockRunnable implements Runnable { A a=new A(); //创建一个A类对象 B b=new B(); //创建一个B类对象 BlockRunnable() //构造方法 { Thread.currentThread().setName("MainThread"); //设置主线程名字 new Thread(this).start(); //创建并启动一个子线程 a.foo(b); //主线程中调用a类的foo方法,foo方法试图调用B类的bar方法 System.out.println("back in the Main thread"); } public void run() { Thread.currentThread().setName("ChildThread"); b.bar(a); System.out.println("back in the ChildThread"); } //主 public static void main(String[] args) { new BlockRunnable(); } }
标签:java
原文地址:http://blog.csdn.net/u012637501/article/details/43125207