同步与死锁:
package com.itheima;
class MyThread implements Runnable{
private int ticket =5;
@Override
public void run() {
for(int i=0; i<50;i++){
if(ticket>0){
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("买票:ticket="+ticket--);
}
}
}
}
public class ThreadName {
public static void main(String[] args) {
MyThread a = new MyThread();
Thread q = new Thread(a,"线程");//系统会自动设置线程的名字
Thread w = new Thread(a,"线程");//系统会自动设置线程的名字
Thread e = new Thread(a,"线程");//系统会自动设置线程的名字
q.start();
w.start();
e.start();
}
}
买票:ticket=5
买票:ticket=4
买票:ticket=3
买票:ticket=2
买票:ticket=1
买票:ticket=0
买票:ticket=-1
package com.itheima;
class MyThread implements Runnable{
private int ticket =5;
@Override
public void run() {
for(int i=0; i<50;i++){
synchronized (this){//设置同步操作
if(ticket>0){
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("买票:ticket="+ticket--);
}
}
}
}
}
public class ThreadName {
public static void main(String[] args) {
MyThread a = new MyThread();
Thread q = new Thread(a,"线程");//系统会自动设置线程的名字
Thread w = new Thread(a,"线程");//系统会自动设置线程的名字
Thread e = new Thread(a,"线程");//系统会自动设置线程的名字
q.start();
w.start();
e.start();
}
}
或者直接同步方法:
package com.itheima;
class MyThread implements Runnable{
private int ticket =5;
@Override
public void run() {
for(int i=0; i<50;i++){
this.sale();
}
}
public synchronized void sale(){//设置同步操作
if(ticket>0){
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("买票:ticket="+ticket--);
}
}
}
public class ThreadName {
public static void main(String[] args) {
MyThread a = new MyThread();
Thread q = new Thread(a,"线程");//系统会自动设置线程的名字
Thread w = new Thread(a,"线程");//系统会自动设置线程的名字
Thread e = new Thread(a,"线程");//系统会自动设置线程的名字
q.start();
w.start();
e.start();
}
}