多线程--打印十次"我爱你"
Posted twqwe
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程--打印十次"我爱你"相关的知识,希望对你有一定的参考价值。
第一种方式: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<=27){
lock.lock();
if(state%3==0){
System.out.println("我");
state ++;
}
lock.unlock();
}
}
});
Thread B=new Thread(new Runnable(){
public void run(){
while(state<=27){
lock.lock();
if(state%3==1){
System.out.println("爱");
state ++;
}
lock.unlock();
}
}
});
Thread C=new Thread(new Runnable(){
public void run(){
while(state<=27){
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<10;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();
}
}
运行结果:
以上是关于多线程--打印十次"我爱你"的主要内容,如果未能解决你的问题,请参考以下文章
POSIX(Linux多线程)使用信号量三个线程顺序打印十次123
东芝笔记本易燃问题数十次召回均"绕开"中国市场,到底是为什么?
从 s = "我爱北京天安门" 中悟道了-----------迭代器操作print(c.__next__())的最!大!好!处!--------------------------