在复习java的过程中,吧学到的代码和大家分享,共同学习。
public class ThreadSynchronize implements Runnable
{
Timer timer = new Timer();
public static void main(String args[])
{
ThreadSynchronize threadSynchronize = new ThreadSynchronize();
Thread thread1 = new Thread( threadSynchronize);
Thread thread2 = new Thread( threadSynchronize);
thread1.setName("t1");
thread2.setName("t2");
thread1.start();
thread2.start();
}
@Override
public void run()
{
timer.add(Thread.currentThread().getName());
}
}
class Timer{
private static int num = 0;
public synchronized void add(String name){//执行当前方法过程中锁定当前对象
num++;
try
{
Thread.sleep(1);
} catch (InterruptedException e)
{
System.out.print(name+"你是第几个" + num+"使用线程");
}
}
}
转载于:https://my.oschina.net/u/657400/blog/113382