[问题] 关于JAVA synchronized的问题?

楼主: SST2000 (BMW 428i)   2020-05-11 08:23:56
请问各位,下面这个范例程式为什么输出只会有线程0执行??
ackage Thread02;
public class main {
public static void main(String[] args) {
Mythread02 T2=new Mythread02();
Thread t1=new Thread(T2);
Thread t2=new Thread(T2);
Thread t3=new Thread(T2);
t1.start();
t2.start();
t3.start();
}
下面是宣告的class
package Thread02;
public class Mythread02 implements Runnable {
private int number=100;
public void run() {
synchronized (this) {
try {
Thread.sleep(100);
//
作者: charlie0275 (派大猩)   2020-05-11 10:02:00
在 main 主执行绪加上sleep多等几秒看看
作者: LZN (秋)   2020-05-11 11:34:00
因为synchronized (this)的关系
作者: ssccg (23)   2020-05-11 14:09:00
在synchronized里面放sleep并不会把lock释放另外以你的写法是抢到的Thread就会一次跑完,如果你是要模拟每个数字都重抢一次,Thread中断应该放在循环里吧while (true) {synchronized (this) {if (...) {...} else { break; }}Thread.sleep(100);}我猜你想做的效果是这样如果一定要synchonized在外面,要用wait/notify来控制lock

Links booklink

Contact Us: admin [ a t ] ucptt.com