<strong>线程同步小例子:开启两个线程实现拿鸡蛋 放鸡蛋交叉进行</strong>
</pre><pre code_snippet_id="574008" snippet_file_name="blog_20150107_1_8603573" name="code" class="java">public class Dofunction { private int num; public synchronized void getEgg(){ while(num==0){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } num--; System.out.println("拿鸡蛋"); notify(); } public synchronized void setEgg(){ while(num!=0){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } num++; System.out.println("放鸡蛋"); notify(); } }
public class TestTread { public static void main(String[] args) { Dofunction set =new Dofunction(); Thread t1 = new GetEgeThread(set); Thread t2 = new Thread(new SetEggThread(set)); t1.start(); t2.start(); } } /** * 对于同一对象而言才存在同步的问题,所以有一个接受对象的构造方法 * */ class SetEggThread implements Runnable { private Dofunction set; public SetEggThread(Dofunction set) { this.set = set; } @Override public void run() { for (int i = 0; i < 20; i++) { set.setEgg(); } } } class GetEgeThread extends Thread { private Dofunction set; public GetEgeThread(Dofunction set) { this.set = set; } @Override public void run() { for (int i = 0; i < 20; i++) { set.getEgg(); } } }
放鸡蛋 拿鸡蛋 放鸡蛋 拿鸡蛋 放鸡蛋 拿鸡蛋 放鸡蛋 拿鸡蛋 放鸡蛋 拿鸡蛋 放鸡蛋 拿鸡蛋 放鸡蛋 拿鸡蛋 放鸡蛋 拿鸡蛋 放鸡蛋 拿鸡蛋 放鸡蛋 拿鸡蛋 放鸡蛋 拿鸡蛋 放鸡蛋 拿鸡蛋 放鸡蛋 拿鸡蛋 放鸡蛋 拿鸡蛋 放鸡蛋 拿鸡蛋 放鸡蛋 拿鸡蛋 放鸡蛋 拿鸡蛋 放鸡蛋 拿鸡蛋 放鸡蛋 拿鸡蛋 放鸡蛋 拿鸡蛋
时间: 2024-10-11 14:32:04