public class Ticket { public static void main(String[] args){ test t = new test(); Thread t1 = new Thread(t); // Thread t2 = new Thread(t); // Thread t3 = new Thread(t); // Thread t4 = new Thread(t);
package com.excel;public class TestTicket { public static void main(String[] args) { Test t = new Test(); Thread t1 = new Thread(t); Thread t2 = new Thread(t); Thread t3 = new Thread(t); Thread t4 = new Thread(t); t1.start(); t2.start(); t3.start(); t4.start(); } }class single { private int k; private single() { k = 1000; }; static single s = new single(); public static single getInstance() { return s; } public int getK() { return k; } public void setK(int k) { this.k = k; } }/** * 实现Runnable接口 */class Test implements Runnable { Object obj = new Object(); public void run() { while (true) { synchronized (obj) { if (single.getInstance().getK() > 0) { System.out.println(Thread.currentThread().getName() + "----" + single.getInstance().getK()); single.getInstance().setK(single.getInstance().getK() - 1); } } } } }没有问题,可能是你看错了
public class Ticket {
public static void main(String[] args){
test t = new test();
Thread t1 = new Thread(t);
// Thread t2 = new Thread(t);
// Thread t3 = new Thread(t);
// Thread t4 = new Thread(t);
t1.start();
// t2.start();
// t3.start();
// t4.start();
}
}
与你之前的代码的结果是一样的,这说明只有t1线程在执行,其他的线程没有执行,跟本没有实现多线程,
而且当t1进入方法锁后,K值减为0后,后面的线程进入run()方法时,if语句已经失效,说以一直会是一条线程。
synchronized(obj)
{
while(true)
{
if(single.getInstance().getK()>0)
{
System.out.println(Thread.currentThread().getName()+"----"+single.getInstance().getK());
single.getInstance().setK(single.getInstance().getK()-1);
}
}
}首先,你用了一个锁,而且你把while(true)放在了同步代码块里面还没有break,那么,这个对象锁永远也不会释放,所以也就只有被第一个持有的线程永久持有了别的线程只能永久等待。
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t); t1.start();
t2.start();
t3.start();
t4.start();
}
}class single {
private int k; private single() {
k = 1000;
}; static single s = new single(); public static single getInstance() {
return s;
} public int getK() {
return k;
} public void setK(int k) {
this.k = k;
}
}/**
* 实现Runnable接口
*/class Test implements Runnable {
Object obj = new Object(); public void run() {
while (true) {
synchronized (obj) { if (single.getInstance().getK() > 0) {
System.out.println(Thread.currentThread().getName()
+ "----" + single.getInstance().getK());
single.getInstance().setK(single.getInstance().getK() - 1);
}
}
}
}
}没有问题,可能是你看错了