java线程同步问题,用了synchronized关键字后不能实现锁定
publicclassTestSyncextendsThread{/***@paramargs*/Timert=newTimer();publicstaticvoidma...
public class TestSync extends Thread{
/**
* @param args
*/
Timer t=new Timer();
public static void main(String[] args) {
TestSync t1=new TestSync();
TestSync t2=new TestSync();
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
public void run(){
t.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.println(name+"你是第"+num+"个访问Timer的线程");
}
}
本来应该打印,第一个和第二个访问timer的线程的,可是打印的时候两个都是第二个,我用了synchronized把方法锁定了啊,为什么还都是第二个呢 展开
/**
* @param args
*/
Timer t=new Timer();
public static void main(String[] args) {
TestSync t1=new TestSync();
TestSync t2=new TestSync();
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
public void run(){
t.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.println(name+"你是第"+num+"个访问Timer的线程");
}
}
本来应该打印,第一个和第二个访问timer的线程的,可是打印的时候两个都是第二个,我用了synchronized把方法锁定了啊,为什么还都是第二个呢 展开
展开全部
你要把你的Timer t=new Timer()设置为static的,不然下面代码中你创建两个TestSync对象,也就有了两个t,然后你的两个线程分别调用不同的t,不能实现锁定,下面是正确代码
---------------------------------------------
public class TestSync extends Thread {
/**
* @param args
*/
static Timer t = new Timer();
public static void main(String[] args) {
TestSync t1 = new TestSync();
TestSync t2 = new TestSync();
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
public void run() {
t.add(Thread.currentThread().getName());
}
}
class Timer {
private static int num = 0;
public synchronized void add(String name) {
num++;
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
System.out.println(name + "你是第" + num + "个访问Timer的线程");
}
}
---------------------------------------------
public class TestSync extends Thread {
/**
* @param args
*/
static Timer t = new Timer();
public static void main(String[] args) {
TestSync t1 = new TestSync();
TestSync t2 = new TestSync();
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
public void run() {
t.add(Thread.currentThread().getName());
}
}
class Timer {
private static int num = 0;
public synchronized void add(String name) {
num++;
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
System.out.println(name + "你是第" + num + "个访问Timer的线程");
}
}
追问
大虾再给看看吧,多谢了~~~
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询