java----------线程学习同步锁

来源:互联网 发布:坏嘟嘟永久域名 编辑:程序博客网 时间:2024/06/05 16:35

在复习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+"使用线程");
}
}
}

原创粉丝点击