同步
package attribute;
public class SaleGoods implements Runnable {
private int num=10;
public synchronized void sellGoods(){
if(num>0){
System.out.println(Thread.currentThread().getName()+"正在出售第"+num+"件商品,"+"还剩"+(--num)+"件商品");
}else {
System.out.println("商品出售完了");
}
}
public void run() {
while (num > 0) {
sellGoods();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package attribute;
public class TestSaleGoods {
public static void main(String[] args){
SaleGoods sell=new SaleGoods();
Thread t1=new Thread(sell,"窗口1");
Thread t2=new Thread(sell,"窗口2");
Thread t3=new Thread(sell,"窗口3");
Thread t4=new Thread(sell,"窗口4");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
运行结果

结束
package attribute;
public class Demo extends Thread{
boolean flag=true;
@Override
public void run() {
if (flag) {
try {
Thread.sleep(1000*60);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("分支线程开始干活!");
}else
{
return;
}
}
}
package attribute;
public class Test {
public static void main(String[] args) throws InterruptedException {
Demo t=new Demo();
t.start();
t.flag=false;
for (int i=0;i<5;i++){
Thread.sleep(100);
System.out.println("分支线程在休眠!------"+i+"秒");
}
}
}


被折叠的 条评论
为什么被折叠?



