本文主要是介绍Java 线程同步问题 synchronized,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package com.threadlifetime.ljb;
/**
* 线程同步问题
* 1.使用synchronized解决(两种方法)
*
*/
public class Threadsynch {
public static void main(String[] args) {
MyThread0 my = new MyThread0();
Thread t1 = new Thread(my);
t1.start();
Thread t2 = new Thread(my);
t2.start();
Thread t3 = new Thread(my);
t3.start();
}
}
class MyThread0 implements Runnable{
private int ticket = 5;
@Override
public void run() {
for (int i = 0; i < 100; i++) {
//解决线程同步问题第一种
synchronized (this) {
if(ticket>0) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("buy ticket:ticket = " + ticket-- );
}
}
}
}
/**
//第二种解决办法
public void run() {
for (int i = 0; i < 100; i++) {
sale();
}
}
synchronized public void sale() {
if(ticket>0) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("buy ticket:ticket = " + ticket-- );
}
}
*/
}
这篇关于Java 线程同步问题 synchronized的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!