⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 threadtest1.java

📁 本java源程序包括了大量的学习程序(共27章)方便大家学习
💻 JAVA
字号:
import java.awt.*;

import javax.swing.*;

//实现Runnable接口
public class ThreadTest1 extends JFrame implements Runnable 
{
    private Thread thread1, thread2;           
    private int x1 = -100;
    private int x2 = -50;
    
    public ThreadTest1()
    {
    	super("多线程1");
			setSize(400,300);
			setBackground(Color.WHITE);            //设置背景色
		
			//创建两个线程
			thread1 = new Thread(this);
			thread2 = new Thread(this);
		
			//启动两个线程
			thread1.start();
			thread2.start();
		
			setVisible(true);
			setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    public void paint(Graphics g)
    {
    	Graphics2D comp2D = (Graphics2D)g;
        comp2D.setColor(getBackground());
        //清除画板
        comp2D.fillRect(0,0,getSize().width,getSize().height);
        
        //绘制矩形
        comp2D.setColor(Color.BLUE);
        comp2D.drawRect(x1, 100, 50, 50);
        
        //绘制圆形
        comp2D.setColor(Color.GREEN);
        comp2D.drawOval(x2, 200, 50, 50);
    	
    }
    //实现Runnable接口的方法run()
    public void run()
    {
    	while(true)
    	{
    		//如果当前线程为thread1则执行以下代码
    		if(Thread.currentThread() == thread1)
    		{
    			x1 += 6;
    			if(x1 >= 500)
    				x1 = -100;
    			repaint();
    			//线程thread1休眠100毫秒
    			pause(100);
    			//如果当前线程为thread2则执行以下代码
    		} 
    		else if(Thread.currentThread() == thread2)
    		{
    			x2 += 4;
    			if(x2 >= 500)
    				x2 = -50;
    			repaint();
    			//线程thread2休眠120毫秒
    			pause(120);
    		}
    	}
    }
    
    //设定线程休眠时间
    private void pause(int time) 
    {
        try 
        {
            Thread.sleep(time);
        } catch (InterruptedException e) {}
    }
    
	public static void main(String[] args) 
	{
		ThreadTest1 test = new ThreadTest1();
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -