java 多线程红绿灯_多线程实现红绿灯循环亮

import java.awt.*;importjava.awt.geom.Ellipse2D;importjava.util.Random;importjava.util.concurrent.locks.Lock;importjava.util.concurrent.locks.ReentrantLock;import javax.swing.*;public class TestThread extendsJFrame{privateThread thread1;privateThread thread2;privateThread thread3;final Lock l = newReentrantLock();private static int state = 0;publicTestThread() {//红灯亮5秒

thread1 = new Thread(newRunnable() {

@Overridepublic voidrun() {while(state>-1) {

l.lock();if(state%3==0) {try{

Thread.sleep(200);

}catch(InterruptedException e) {

e.printStackTrace();

}

Graphics graphics=getGraphics();

Graphics2D graphics2d=(Graphics2D) graphics;

Shape shape= new Ellipse2D.Double(30,60,100,100);

graphics.setColor(Color.red);

graphics2d.fill(shape);try{

Thread.sleep(5000);

}catch(InterruptedException e) {

e.printStackTrace();

}

graphics.clearRect(30, 60, 100, 100);

state++;

}

l.unlock();

}

}

});//黄灯亮2秒

thread2 = new Thread(newRunnable() {

@Overridepublic voidrun() {while(state>-1) {

l.lock();if(state%3==1) {try{

Thread.sleep(0);

}catch(InterruptedException e) {

e.printStackTrace();

}

Graphics graphics=getGraphics();

Graphics2D graphics2d=(Graphics2D) graphics;

Shape shape1= new Ellipse2D.Double(180,60,100,100);

graphics.setColor(Color.yellow);

graphics2d.fill(shape1);try{

Thread.sleep(2000);//等待2秒

} catch(InterruptedException e) {//TODO 自动生成的 catch 块

e.printStackTrace();

}

graphics.clearRect(180, 60, 100, 100);//清除

state++;

}

l.unlock();

}

}

});//路灯亮4秒

thread3 = new Thread(newRunnable() {

@Overridepublic voidrun() {while(state>-1) {

l.lock();if(state%3==2) {try{

Thread.sleep(0);

}catch(InterruptedException e) {

e.printStackTrace();

}

Graphics graphics=getGraphics();

Graphics2D graphics2d=(Graphics2D) graphics;

Shape shape2= new Ellipse2D.Double(330,60,100,100);//设置圆的位置

graphics.setColor(Color.green);//颜色

graphics2d.fill(shape2);//填充

try{

Thread.sleep(3500);

}catch(InterruptedException e) {

e.printStackTrace();

}

graphics.clearRect(330, 60, 100, 100); //清除圆

state++;

}

l.unlock();

}

}

});//启动线程

thread1.start();

thread2.start();

thread3.start();

}public static void init(JFrame jFrame,int width,intheight) {

jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//窗口关闭方式

jFrame.setSize(width, height);//窗口大小

jFrame.setVisible(true);//可见

}public static voidmain(String[] args) {

init(new TestThread(), 500, 200);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值