java多线程例子(7)

2021-01-26 23:19

介绍java多线程例子

Thread-2 is saling 1

Thread-3 is saling 0

Thread-0 is saling -1

Thread-1 is saling -2

卖出了0、-1和-2的票,证明上述这种写法是存在线程安全的。

线程同步

为了解决线程安全的问题,就要引入线程同步。

class ThreadDemo {

public static void main(String[] args) {

TestThread t = new TestThread();

new Thread(t).start();

new Thread(t).start();

new Thread(t).start();

new Thread(t).start();

}

}

class TestThread implements Runnable {

int tickets = 100;

String str = ""; //此时str为公共对象

public void run() {

while(true) {

synchronized(str) {

if(tickets<=0)

break;

//try{Thread.sleep(10);}catch(Exception e) {}

System.out.println(Thread.currentThread().getName() + " is saling " + tickets--);

}

}

}

}

在上面的代码中加入synchronized,就可以实现线程同步了。

运行结果 写道

hread-2 is saling 5

hread-3 is saling 4

hread-1 is saling 3


java多线程例子(7).doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:氧气吸入操作流程

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: