java中二种方法实现一个线程
2011-02-24 16:44
246 查看
有两种方法,一种是继承Thread类,另一种是实现Runable接口
(1)
public class Test{
public static void main(String [] args){
MyThread mt=new MyThread();
mt.start();
}
}
class MyThread extends Thread{//继承Thread类
int count=0;
public void run(){//重写run()方法
while(true){
System.out.println("MyThread is running !"+count+"times");
try{
sleep(1000);//每隔1m输出
count++;
}catch(InterruptedException e){//扑捉可能产生的中断异常(非运行时异常)
System.out.println("产生中断异常");
}
if(count==10)return;
}
}
}
(2)
public class Test{
public static void main(String [] args){
RunableDemo rd=new RunableDemo();
Thread t=new Thread(rd);
t.start();
}
}
class RunableDemo implements Runable{//实现Runable接口
int count=0;
public void run(){//重写run()方法
while(true){
System.out.println("MyThread is running !"+count+"times");
try{
Thread.sleep(1000);//静态方法,可以用类名直接调用
count++;
}catch(InterruptedException e){//扑捉可能产生的中断异常
System.out.println("产生中断异常");
}
if(count==10)return;
}
}
}
}
(1)
public class Test{
public static void main(String [] args){
MyThread mt=new MyThread();
mt.start();
}
}
class MyThread extends Thread{//继承Thread类
int count=0;
public void run(){//重写run()方法
while(true){
System.out.println("MyThread is running !"+count+"times");
try{
sleep(1000);//每隔1m输出
count++;
}catch(InterruptedException e){//扑捉可能产生的中断异常(非运行时异常)
System.out.println("产生中断异常");
}
if(count==10)return;
}
}
}
(2)
public class Test{
public static void main(String [] args){
RunableDemo rd=new RunableDemo();
Thread t=new Thread(rd);
t.start();
}
}
class RunableDemo implements Runable{//实现Runable接口
int count=0;
public void run(){//重写run()方法
while(true){
System.out.println("MyThread is running !"+count+"times");
try{
Thread.sleep(1000);//静态方法,可以用类名直接调用
count++;
}catch(InterruptedException e){//扑捉可能产生的中断异常
System.out.println("产生中断异常");
}
if(count==10)return;
}
}
}
}
相关文章推荐
- 一个方法最多2个线程同时使用的JAVA实现
- 【Java面试题】23 java中有几种方法可以实现一个线程?用什么关键字修饰同步方法? stop()和suspend()方法为何不推荐使用?
- java中俩种方法实现一个线程,以及不推荐使用stop()和suspend()方法
- java中有几种方法可以实现一个线程?用什么关键字修饰同步方法? stop()和suspend()方法为何不推荐使用?
- java中有几种方法可以实现一个线程?用什么关键字修饰同步方法 stop()和suspend()方法为何不推荐使用?
- java中可以实现一个线程的方法
- Java在实现方法中新开一个线程
- 【Java面试题】26 多线程有几种实现方法?同步有几种实现方法? 当一个线程进入一个对象的一个synchronized方法后,其它线程是否可进入此对象的其它方法?
- java 中有几种方法可以实现一个线程? 用什么关键字修 饰同步方法? stop()和 suspend()方法为何不推荐使用?
- Java 有几程方法可以实现一个线程?用什么关键字修饰同步?stop()和suspend()为什么不推荐使用?
- java有几种方法可以实现一个线程?用什么关键字修饰同步方法?
- Java中有几种方法实现一个线程,用什么关键字修饰同步方法?stop()和suspend()方法为何不提倡使用?
- java中有几种方法可以实现一个线程?用什么关键字修饰同步
- java开发线程篇1:java中有几种方法可以实现一个线程?用什么关键字修饰同步方法? stop()和suspend()方法为何不推荐使用?
- JAVA线程之一:实现一个线程的两种方法
- java中有几种方法可以实现一个线程?
- java基础问题---java中有几种方法可以实现一个线程?用什么关键字修饰同步方法? stop()和suspend()方法为何不推荐使用
- java中有几种方法可以实现一个线程?用什么关键字修饰同步方法? stop()和suspend()方法为何不推荐使用
- java中有几种方法可以实现一个线程
- Java中有几种方法可以实现一个线程