多线程--打印十次"我爱你"

2021-05-16 00:29

阅读:449

标签:you   操作   ++   exception   lov   str   ant   for   运行   

第一种方式:Lock锁

package com.test;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadDemo {
private static int state=0;
public static void main(String[] args) {
final Lock lock=new ReentrantLock();

Thread A=new Thread(new Runnable(){
public void run(){

while(state lock.lock();
if(state%3==0){
System.out.println("我");
state ++;
}
lock.unlock();
}
}
});

Thread B=new Thread(new Runnable(){
public void run(){

while(state lock.lock();
if(state%3==1){
System.out.println("爱");
state ++;
}
lock.unlock();
}
}
});

Thread C=new Thread(new Runnable(){
public void run(){

while(state lock.lock();
if(state%3==2){
System.out.println("你");
state ++;
}
lock.unlock();
}
}
});

A.start();
B.start();
C.start();

}

}
运行结果如下:

技术分享图片

第二种:synchronized同步方法:

具体代码如下:

package com.test;
public class ThreadDemo2 implements Runnable{


//三个变量 三条线程之间切换执行 一把锁是不够的 2把锁把锁 对象有锁的定义 Object对象

private String word;//线程要打印的字
private Object prev;//当前线程的上一个线程要持有的锁
private Object current;//当前线程所要持有的锁

public void run() {
for(int i=0;i synchronized (prev){
synchronized (current){
System.out.println(word);
current.notify();
}
try {
prev.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public ThreadDemo2(String word, Object prev, Object current) {
this.word = word;
this.prev = prev;
this.current = current;
}
//打印字的操作
}


测试类:

package com.test;

public class TestThreadDemo2 {
public static void main(String[]args) throws Exception{
Object a=new Object();
Object b=new Object();
Object c=new Object();
Thread t1=new Thread(new ThreadDemo2("I",c,a));
Thread t2=new Thread(new ThreadDemo2("love",a,b));
Thread t3=new Thread(new ThreadDemo2("you",b,c));
t1.start();;
Thread.sleep(1000);
t2.start();;
Thread.sleep(1000);
t3.start();
}
}

运行结果:

技术分享图片

 


 


多线程--打印十次"我爱你"

标签:you   操作   ++   exception   lov   str   ant   for   运行   

原文地址:https://www.cnblogs.com/twqwe/p/9750004.html


评论


亲,登录后才可以留言!