/**
* 多线程的含义是:多个线程操作的是同一个对象
*/
public class MyThread003 implements Runnable
{
private static final String TAG = "MyThread003";
private int apple = 100;
synchronized public void sell()//方法锁
{
System.out.println(Thread.currentThread().getName() + "卖出了第" + " " + apple + " " + "apple");
--apple;
}
public int getApple()
{
return apple;
}
@Override
public void run()
{
while (getApple() > 0)
{
sell();
try
{
Thread.sleep(200);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("卖光了!");
}
public static void main(String[] args)
{
MyThread003 m3 = new MyThread003();//对象
Thread t1 = new Thread(m3, "zhanlo");//线程1
Thread t2 = new Thread(m3, "lisi");//线程2
Thread t3 = new Thread(m3, "jhon");//线程3
Thread t4 = new Thread(m3, "puple");//线程4
t1.start();
t2.start();
t3.start();
t4.start();
}
}
Java多线程2
最新推荐文章于 2023-06-14 17:20:14 发布