注册 登录
编程论坛 JAVA论坛

关于多线程的demo

疯狂的小a 发布于 2018-08-23 14:56, 2870 次点击
项目结构
只有本站会员才能查看附件,请 登录

一直跑的线程
程序代码:
package com.xiaoa.thread;

public class Mythread implements Runnable {
    int tickets = 100;//線程共享的成員變量

    @Override
    public void run() {
        while (true) {
            if (tickets > 0) {
                System.out.println(Thread.currentThread().getName()+"卖出的第" + tickets-- + "张票");
            }
        }
    }

测试1,一切看似正常
程序代码:
package com.xiaoa.test;

import com.xiaoa.thread.Mythread;

public class ThreadTest {
    public static void main(String[] args) {
        Mythread tt = new Mythread();
        Thread t1 = new Thread(tt);//構造的線程必須傳入相同的runable,才可以共享成員變量
        Thread t2 = new Thread(tt);
        t1.setName("售票窗口1");
        t2.setName("售票窗口2");
        t1.start();
        t2.start();
    }
}
只有本站会员才能查看附件,请 登录

小睡一会的线程
程序代码:
package com.xiaoa.thread;

public class Mythread2 implements Runnable {
    int tickets = 100;//線程共享的成員變量

    @Override
    public void run() {
        while (true) {
            try {
                Thread.currentThread().sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (tickets > 0) {
                System.out.println(Thread.currentThread().getName()+"卖出的第" + tickets-- + "张票");
            }
        }
    }

}
测试2,发现了线程不安全的诡异问题
程序代码:
package com.xiaoa.test;

import com.xiaoa.thread.Mythread2;

public class ThreadTest2 {
    public static void main(String[] args) {
        Mythread2 tt = new Mythread2();
        Thread t1 = new Thread(tt);//構造的線程必須傳入相同的runable,才可以共享成員變量
        Thread t2 = new Thread(tt);
        t1.setName("售票窗口1");
        t2.setName("售票窗口2");
        t1.start();
        t2.start();
    }
}
只有本站会员才能查看附件,请 登录




[此贴子已经被作者于2018-8-23 14:58编辑过]

3 回复
#2
new_bigbug2018-09-23 11:04
会不会是没有将run()方法里的内容原子化呢?
程序代码:
public void run() {
        while (true) {
            synchronized(this)//加入这句应该可以解决吧
            {
                try {
                    Thread.currentThread().sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (tickets > 0) {
                    System.out.println(Thread.currentThread().getName()+"卖出的第" + tickets-- + "张票");
                }
            }
        }
    }
#3
melody872019-02-27 15:17
同步,楼上正解
#4
GrayJerry2019-09-26 19:55
二楼正解,多个线程在访问同一份资源时,需要加:同步
1