import java.io.*;
import java.lang.*;
import java.util.*;
public class hehe implements Runnable{
Timer ti = new Timer();
public static void main(String args[]){
hehe he = new hehe();
Thread t1 = new Thread(he);
Thread t2 = new Thread(he);
t1.start();
t2.start();
}
public void run(){
ti.add(Thread.currentThread().getName());
}
}
public class Timer {
private static int num = 0;
public void add(String name){
synchronized(this){
num++;
try{
Thread.sleep(1);
}catch(Exception e){
return ;
}
System.out.println(name+" "+num);
}
}
}
或者是直接在方法名字的前面加上synchronized关键字
Java多线程同步示例
本文通过一个Java示例程序介绍了如何使用synchronized关键字来实现多线程间的同步操作,确保了线程安全。该示例展示了两个线程如何共享资源并按顺序执行任务。
1220

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



