线程处理
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()+"在睡眠!");
}
}