public class ThreadTest4 implements Runnable
{
Timer timer = new Timer();
public static void main(String[] args)
{
ThreadTest4 t1 = new ThreadTest4();
ThreadTest4 t2 = new ThreadTest4();
Thread thread1 = new Thread(t1,"t1");
Thread thread2 = new Thread(t2,"t2");
thread1.start();
thread2.start();
}
public void run()
{
timer.add(Thread.currentThread().getName());
}
}class Timer
{
private static int number = 0;
public synchronized void add(String name)
{
number++;
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println(name+",你是第"+number+"个");
}
}输出:t1,你是第2个
t2,你是第2个方法已经加锁了,为什么还是会出现两个线程访问一个加锁的方法的问题?
无所谓同步
您是弄了两个thread同时操作两个timer,所以锁不上的。正好你又搞了一个static变量,最后就累加成2了。真想玩锁的话,我告诉一招。
class Timer {
private static int number = 0;
public void add(String name) {
synchronized (Timer.class) {
number++;
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+",你是第"+number+"个");
}
}
}像这样,既然锁就要锁一个jvm中独一无二的东东。记得还必须是object,基础类型锁不到。
ThreadTest4 t1 = new ThreadTest4();
ThreadTest4 t2 = new ThreadTest4();
Thread thread1 = new Thread(t1,"t1");
Thread thread2 = new Thread(t2,"t2");
这个t1和t2是不同对象的两个线程是不能对他们进行加锁可以怎么说thread1和thread2
是两个不相关的线程不能进行加锁应该改成:ThreadTest4 t1 = new ThreadTest4();
Thread thread1 = new Thread(t1,"t1");
Thread thread2 = new Thread(t1,"t2");
如此上面threa1和thread2就是同一个对象的两个线程就完全可以对进行加锁了。
帮你改正后的代码为:public class ThreadTest4 implements Runnable
{
Timer timer = new Timer(); public static void main(String[] args)
{
ThreadTest4 t1 = new ThreadTest4();
Thread thread1 = new Thread(t1,"t1");
Thread thread2 = new Thread(t1,"t2");
thread1.start();
thread2.start();
} public void run()
{
timer.add(Thread.currentThread().getName());
}
}class Timer
{
private static int number = 0; public synchronized void add(String name)
{
number++;
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println(name+",你是第"+number+"个");
}
}