public class TextThread {
public static void main(String[] args) {
TxtThread tt = new TxtThread();
new Thread(tt).start();
new Thread(tt).start();
try {
Thread.sleep(1000);
}catch (Exception e) {
e.getMessage();
}
}
}
class TxtThread implements Runnable {
int num = 10;
String str = new String();
public void run() {
synchronized (str) {
while (num > 0) {
try {
Thread.sleep(1);
}catch (Exception e) {
e.getMessage();
}
System.out.println(Thread.currentThread().getName() + "this is " + num--);
}
}
}
}
synchronized 代码块保证两个线程只有一个能够访问这块代码,其他的线程被阻塞,直到前面的线程执行完毕。但是上面这个例子,始终只有一个线程能执行,一个执行完之后另外的线程却不执行。请问这是怎么回事呢?请大神指点。
public static void main(String[] args) {
TxtThread tt = new TxtThread();
new Thread(tt).start();
new Thread(tt).start();
try {
Thread.sleep(1000);
}catch (Exception e) {
e.getMessage();
}
}
}
class TxtThread implements Runnable {
int num = 10;
String str = new String();
public void run() {
synchronized (str) {
while (num > 0) {
try {
Thread.sleep(1);
}catch (Exception e) {
e.getMessage();
}
System.out.println(Thread.currentThread().getName() + "this is " + num--);
}
}
}
}
synchronized 代码块保证两个线程只有一个能够访问这块代码,其他的线程被阻塞,直到前面的线程执行完毕。但是上面这个例子,始终只有一个线程能执行,一个执行完之后另外的线程却不执行。请问这是怎么回事呢?请大神指点。