package Thanqi;
public class TestApple implements Runnable{
//苹果的数量
private int count = 5;
//拿苹果
//synchronized 线程同步关键字
private void getapple()
{
synchronized (this){
if(count<=0)
{
System.out.println(Thread.currentThread().getName()+"没有苹果了");
return;
}
count--;
System.out.println(Thread.currentThread().getName()+"拿了一个苹果,苹果还剩"+count);
}}
public void run()
{
//连续拿苹果
while(count>0)
{
getapple();
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// // TODO 自动生成的 catch 块
// e.printStackTrace();
// }
}
// for(int i= 0;count>0;i++)
// {
//
// }
}
}
package Thanqi;
public class Test05 {
public static void main(String[] args){
//测试线程同步
//强苹果
TestApple ta= new TestApple();
//第一个线程 小明
Thread t1 = new Thread(ta);
t1.setName("小明");
t1.start();
Thread t2= new Thread(ta,"小强");
t2.start();
}
}