public class Threadtest extends Thread{
private static long number=0;
Object a=new Object();
public Threadtest(){
}
public synchronized void go(){
number++;
System.out.println("当前值:"+number);
}
public void run(){
for(;;){
go();
try {
Thread.sleep(1000); //test 间隔1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} /**
* @param args
*/
public static void main(String[] args) {
Threadtest[] statethread=new Threadtest[10];
for(int i=0;i<statethread.length;i++){
statethread[i]=new Threadtest();
statethread[i].start();
} }}
我的目的就是每个线程数字的加1和输出能够顺序执行,在打印的结果中每个数字只打印一次(顺序无所谓)
请大家指点!
private static long number=0;
Object a=new Object();
public Threadtest(){
}
public synchronized void go(){
number++;
System.out.println("当前值:"+number);
}
public void run(){
for(;;){
go();
try {
Thread.sleep(1000); //test 间隔1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} /**
* @param args
*/
public static void main(String[] args) {
Threadtest[] statethread=new Threadtest[10];
for(int i=0;i<statethread.length;i++){
statethread[i]=new Threadtest();
statethread[i].start();
} }}
我的目的就是每个线程数字的加1和输出能够顺序执行,在打印的结果中每个数字只打印一次(顺序无所谓)
请大家指点!
你应该在go方法中写
synchronized(this.class){
......
}
才能达到你要的目的。 我发现很多人没有搞清楚锁对象和所类的区别,包括在很多论坛的教程里面,都是认为简单的在方法上加上synchronized就可以线程安全了。
你应该写一个标志一样的.
如你定义一个static 变量 ,用static变量来同步
这样
public static void main(String[] args) {
Thread test=new Threadtest();
for(int i=0;i<10;i++){
test.start();
} }
public class Threadtest extends Thread
改为
public class Threadtest implements Runnable
{
}
然后在main方法中
public static void main(String[] args) {
Threadtest test=new Threadtest();
Thread [] tt = new Thread[10];
for(int i=0;i<tt.length;i++){
tt[i]=new Thread(test);
tt[i].start();
}
}
import java.io.*;
import java.awt.*;class MyValue {
private long i = 0;
public synchronized long getI() {
return i++;
}
}class MyThread extends Thread {
private MyValue i;
public MyThread(String s, MyValue x) {
super(s);
i = x;
}
public void run() {
while(true){
System.out.println(getName() + " " + i.getI());
yield();
}
}
}public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
//设置一个定时器,程序100毫秒后结束
(new Timer()).schedule(new TimerTask(){
public void run(){
System.exit(0);
}
},100);
MyValue mv = new MyValue();
MyThread[] mt = new MyThread[10];
for(int i=1; i<=10; i++) {
mt[i-1] = new MyThread("线程"+i, mv);
mt[i-1].start();
}
// System.out.println("");
}}