package thread;
/*
* 线程同步机制
* 同步块
* 在java中提供了同步机制,可以有效防止资源冲突。
* 同步机制使用synchronized关键字
*/
public class ThreadSafeTest1 implements Runnable{
int num=10;
public static void main(String[] args) {
ThreadSafeTest1 t=new ThreadSafeTest1();
Thread tA=new Thread(t);
Thread tB=new Thread(t);
Thread tC=new Thread(t);
Thread tD=new Thread(t);
tA.start();
tB.start();
tC.start();
tD.start();
}
@Override
public void run() {
while(true){
synchronized("") {
if(num>0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("tickets"+num--);
}
}
}
}
}
/*
* 线程同步机制
* 同步块
* 在java中提供了同步机制,可以有效防止资源冲突。
* 同步机制使用synchronized关键字
*/
public class ThreadSafeTest1 implements Runnable{
int num=10;
public static void main(String[] args) {
ThreadSafeTest1 t=new ThreadSafeTest1();
Thread tA=new Thread(t);
Thread tB=new Thread(t);
Thread tC=new Thread(t);
Thread tD=new Thread(t);
tA.start();
tB.start();
tC.start();
tD.start();
}
@Override
public void run() {
while(true){
synchronized("") {
if(num>0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("tickets"+num--);
}
}
}
}
}
本文介绍了一个使用Java实现的线程安全示例。通过synchronized关键字确保了在多线程环境下对共享资源的安全访问。该示例展示了如何通过同步块来避免竞态条件,从而保证了程序的正确执行。
328

被折叠的 条评论
为什么被折叠?



