黑马程序员-java-多线程2

------ Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------


通过实现Runnable接口来创建多线程的实例

采用了同步的第一种方式:synchronized


package cn.tt910;


public class SellTic implements Runnable{
private int t=100;
//创建锁
private Object obj=new Object();
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
synchronized(obj){
if(t>0){
//为了模拟真实场景,sleep
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"正在出售: "+(t--));
}
}
}
}
}



package cn.tt910;


public class Test03 {
public static void main(String[] args) {
SellTic st=new SellTic();
Thread t1=new Thread(st,"窗口1");
Thread t2=new Thread(st,"窗口2");
Thread t3=new Thread(st,"窗口3");

t1.start();
t2.start();
t3.start();
}
}


你可能感兴趣的:(黑马程序员-java-多线程2)