public class Ticket implements Runnable{
private int tick = 100;
Object obj = new Object();
@Override
public void run() {
while (true)
{
synchronized(obj){ //同步多线程,传入synchronized的对象需要在run方法之前创建!否则也是不能同步
if (tick >0)
{
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
/**
* 打印 “线程名称 + 票数 ”
* 使用静态方法解决
*/
System.out.println( Thread.currentThread().getName()+": " + tick--);
}
}
}
}
public static void main (String argc[])
{
Ticket t = new Ticket();
Thread thread1 = new Thread( t, "t1");
Thread thread2 = new Thread( t, "t2");
Thread thread3 = new Thread( t, "t3");
Thread thread4 = new Thread( t, "t4");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
java同步多线程
最新推荐文章于 2024-09-03 20:17:53 发布