线程的处理

线程处理

package Thread;

public class RunnableTest {

	public static void main(String[] args) {
		// 创建线程以MyRunnable的对象为目标对象
		Thread thread1 = new Thread(new MyRunnable(300,0), "Thread1");
		Thread thread2 = new Thread(new MyRunnable(500,1), "Thread2");

		// 启动线程
		thread1.start();
		thread2.start();
	}
}

class MyRunnable implements Runnable 
{
	private RunnableTest tr;
	private int sleepTime;
	private String s;
	int a[]=new int[2];
	int j;
	// 构造函数
	public MyRunnable(int time,int i) 
	{
		sleepTime = time;
		j=i;
		a[j]=0;
	}

	// 控制线程的执行

	public void run() 
	{
		while(a[j]<3)
		{
			
				// 让当前执行的线程睡眠
				try {
					Thread.sleep(sleepTime);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// 取得当前执行的线程名
				s = Thread.currentThread().getName();
				System.out.println("线程名:" + s);
				if (a[j]==0) {
					System.out.println("线程启动啦!");
				}
				else if(a[j]>0&&a[j]<3)
				{
					System.out.println("线程在运行");
				}
				a[j]++;
				System.out.println(a[j]);
		} 
		System.out.println("线程结束啦!");
	}
}

2

package Thread;

public class ThreadTest
{
  public static void main(String[] args) 
  {
	  MyThread thread1,thread2,thread3,thread4;
	  
	  //创建线程
	  thread1=new MyThread("thread1");
	  thread2=new MyThread("thread2");
	  thread3=new MyThread("thread3");
	  thread4=new MyThread("thread4");
	  
	  //启动线程
	  thread1.start();
	  thread2.start();
	  thread3.start();
	  thread4.start();

	  System.out.println("线程已经启动!\n");
	}
}
 class MyThread extends Thread
 {
	private int sleepTime;
	void method()  //非成员方法
	{
		
	}
	protected String returnString()   //保护类型的成员方法
	{
		return "abc";
	}
	//构造函数
	public MyThread(String name)
	{
		//调用父类构造函数
		super(name);
		
		//睡眠0-5秒
		sleepTime=(int)(Math.random()*5000);
		
		//显示线程名以及睡眠时间
		System.out.println("线程名:"+getName()+"; 睡眠时间:"+sleepTime);
	}
	//控制线程的执行
	public void run()
	{
		//让线程睡眠一随机时间
		try
		{
			System.out.println(getName()+"即将睡眠!");
			
			//将线程转入睡眠状态
			Thread.sleep(sleepTime);
		}
		//如果线程在睡眠状态被中断执行,则显示错误信息
		catch(InterruptedException interruptedException)
		{
		System.err.println(interruptedException.toString());
		}
		//显示正睡眠的线程
		System.out.println(getName()+"在睡眠!");
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值