public class BB extends Thread {
int time;
public BB (int t) {
this.time = t;
}
public synchronized void run() {
for(int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " " + i + "次");
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(i ==5) {
System.out.println(Thread.currentThread().getName() + "退出了");
}
}
}
public static void main(String[] args) {
BB b1 = new BB(500);
b1.setName("线程1");
b1.start();
BB b2 = new BB(200);
b2.setName("线程2");
b2.start();
BB b3 = new BB(300);
b3.setName("线程3");
b3.start();
}
}run()方法中有synchronized修饰符,为什么还是不能实现同步,输出结果仍然是无序的啊???
static Object obj = new Object();
int time;
....
public void run() {
synchronized(obj){
//... 你的代码
}
}}你这样试试
lz不妨试试让BB实现Runnable接口main方法中
BB bb = new BB();
Thread b1 = new Thread(BB);
b1.setName(...);
start();
Thread b2 = new Thread(BB);
b2.setName(...);
b2.start();
...
这个方法,其实是针对当前对象加锁,所以,你new三个对象的话,有三个不同的锁,他们互不相干,当然就不能实现同步了。
这种写法,想表达的意思是,对于单一的一个BB对象,如果有多个线程调用其run方法,可以达到同步效果。
run方法能叫共有的方法吗
每个线程开启都会有自己的run方法
开启一个线程就会有自己的一个run();
楼主相当于有四条线程 一个主线程
三个分支线程 而这三个线程都有自己的run()方法 分开进行 互不影响!!!
| | | |
| | | |
| | | |
主 线1(run) 线2(run)线3(run)
用你自己的程序和5楼的程序运行下,看看输出。
int time;
public BB (int t) {
this.time = t;
}
public void run() {
synchronized (BB.class)
for(int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " " + i + "次");
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(i ==5) {
System.out.println(Thread.currentThread().getName() + "退出了");
}
}
}
}
public static void main(String[] args) {
BB b1 = new BB(500);
b1.setName("线程1");
b1.start();
BB b2 = new BB(200);
b2.setName("线程2");
b2.start();
BB b3 = new BB(300);
b3.setName("线程3");
b3.start();
}
}关键是锁用的不对,改为如上的用法就可以了。
有什么问题可以再问我
}
package bb;public class BB implements Runnable { int time; public BB(int t) {
time = t;
} @Override
public synchronized void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " " + i + "次");
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (i == 5) {
System.out.println(Thread.currentThread().getName() + "退出了");
}
}
} public static void main(String[] args) {
BB b = new BB(500);
new Thread(b).start();
new Thread(b).start();
new Thread(b).start();
}
}多线程共享需要使用Runnable哦~不过这样就不能分别设置sleep时间了.
@Override
public synchronized void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " " + i + "次");
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (i == 5) {
System.out.println(Thread.currentThread().getName() + "退出了");
time -= 200;
}
}
}