多线程交替打印
1.使用synchronized加锁方式
public class test {
public static void main(String[] args) {
Count c = new Count(0);
new Thread(()->{
c.even();
}).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
c.odd();
}).start();
}
}
class Count{
private int count;
public Count(int count){
this.count = count;
}
public void odd(){
synchronized (this){
while(count<100){
System.out.println(count++);
this.notify();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void even(){
synchronized (this){
while (count<=100){
System.out.println(count++);
this.notify();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
2.使用volatile关键字
public class test1 {
public static void main(String[] args) {
Resource re = new Resource(0);
new Thread(()->{
re.even();
}).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
re.odd();
}).start();
}
}
class Resource{
volatile int count;
volatile int flag;
public Resource(int count){
this.count = count;
this.flag = 0;
}
public void odd(){
while (count<100){
if(flag==1){
System.out.println(Thread.currentThread().getName()+count);
count++;
flag--;
}
}
}
public void even(){
while (count<=100){
if(flag==0){
System.out.println(Thread.currentThread().getName()+count);
count++;
flag++;
}
}
}
}