鄙人java新手入门,自学线程同步的时候有这样的一个疑问,如下
public class Example13 {
public static void main(String[] args){
Ticket13 ticket=new Ticket13();
new Thread(ticket,"窗口一").start();
new Thread(ticket,"窗口二").start();
new Thread(ticket,"窗口三").start();
new Thread(ticket,"窗口四").start();
}
}
class Ticket13 implements Runnable{
int i=20;
public void run(){
while (true) {
if (i>0) {
saleTicket();
}else {
break;
}
}
}
private synchronized void saleTicket(){
System.out.println(Thread.currentThread().getName() + "正在出票" + i--);
}
}
这是代码一
package chapter5;
public class Example13 {
public static void main(String[] args){
Ticket13 ticket=new Ticket13();
new Thread(ticket,"窗口一").start();
new Thread(ticket,"窗口二").start();
new Thread(ticket,"窗口三").start();
new Thread(ticket,"窗口四").start();
}
}
class Ticket13 implements Runnable{
int i=20;
public void run(){
while (true) {
saleTicket();
if (i<=0) {
break;
}
}
}
private synchronized void saleTicket(){
System.out.println(Thread.currentThread().getName() + "正在出票" + i--);
}
}
这是代码二
在我理解上这两个所实现的效果没有区别,但是代码一就一直执行窗口一,代码二就会出现其他的窗口
public class Example13 {
public static void main(String[] args){
Ticket13 ticket=new Ticket13();
new Thread(ticket,"窗口一").start();
new Thread(ticket,"窗口二").start();
new Thread(ticket,"窗口三").start();
new Thread(ticket,"窗口四").start();
}
}
class Ticket13 implements Runnable{
int i=20;
public void run(){
while (true) {
if (i>0) {
saleTicket();
}else {
break;
}
}
}
private synchronized void saleTicket(){
System.out.println(Thread.currentThread().getName() + "正在出票" + i--);
}
}
这是代码一
package chapter5;
public class Example13 {
public static void main(String[] args){
Ticket13 ticket=new Ticket13();
new Thread(ticket,"窗口一").start();
new Thread(ticket,"窗口二").start();
new Thread(ticket,"窗口三").start();
new Thread(ticket,"窗口四").start();
}
}
class Ticket13 implements Runnable{
int i=20;
public void run(){
while (true) {
saleTicket();
if (i<=0) {
break;
}
}
}
private synchronized void saleTicket(){
System.out.println(Thread.currentThread().getName() + "正在出票" + i--);
}
}
这是代码二
在我理解上这两个所实现的效果没有区别,但是代码一就一直执行窗口一,代码二就会出现其他的窗口