首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

进程 同步有关问题

2013-07-01 
进程 同步问题class MyThread implements Runnable{private int ticket10public void run(){synchronize

进程 同步问题
class MyThread implements Runnable{
private int ticket=10;
public void run(){
synchronized(this){
for(int i=0;i<100;i++){
if(ticket>0){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"卖掉第"+ticket--+"张票");
}
}
}
}
}
public class SynchronizedDemo{
public static void main(String args[]){
MyThread mt=new MyThread();
Thread t1=new Thread(mt,"窗口1");
Thread t2=new Thread(mt,"窗口2");
Thread t3=new Thread(mt,"窗口3");
t1.start();
t2.start();
t3.start();
}
}
进程 同步有关问题
为什么只有一个窗口买票,而不是三个窗口同时买票,求大神分析一下 线程 同步
[解决办法]
下面是我修改后的代码,希望对你有帮助:


package zhangming.csdn;

class MyThread implements Runnable
{
private int ticket=10;
public void run()
{

for(int i=0;i<10;i++)//建议不要将i的最大值设的太大这样太浪费资源
{
//先睡眠,后锁定,以便让其他线程进来
try
{
Thread.sleep(1000);
}catch(InterruptedException e){e.printStackTrace();}
//在进行售票时,需要进行锁定
synchronized(this)
{
if(ticket>0)
{
System.out.println(Thread.currentThread().getName()+"卖掉第"+ticket--+"张票");
}
}
}
}
}
public class SynchronizedDemo
{
public static void main(String args[])
{
MyThread mt=new MyThread();
Thread t1=new Thread(mt,"窗口1");
Thread t2=new Thread(mt,"窗口2");
Thread t3=new Thread(mt,"窗口3");
t1.start();
t2.start();
t3.start();
}
}

[解决办法]
仅供参考:

class MyThread implements Runnable {
private int ticket = 10;

public void run() {
while (ticket > 0) {//循环条件


try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (this) {
if (ticket > 0) {//避免卖 -1 张票。
System.out.println(Thread.currentThread().getName() + "卖掉第"
+ ticket-- + "张票");
} else {
break;//退出
}
}
}
}
}

public class SynchronizedDemo {
public static void main(String args[]) {
MyThread mt = new MyThread();
Thread t1 = new Thread(mt, "窗口1");
Thread t2 = new Thread(mt, "窗口2");
Thread t3 = new Thread(mt, "窗口3");
t1.start();
t2.start();
t3.start();
}
}

热点排行