如何创建线程,简单代码

1、实现线程的方法:(1)继承Thread类重写run方法

                                      (2)实现Runnable接口重写un方法

                                      (3)实现Callable接口通过FutureTask包装器来创建Thread线程

                                      (4)利用线程池(newCachedThreadPool、newFixedThreadPool )

1、继承Thread类

(1)线程类
public class MyThread extends Thread {  
  public void run() {       //不会创建新的线程,相当于只是一个普通方法,由当前线程来调用
   System.out.println("MyThread.run()");  
  }  
}  
(2)测试类
MyThread myThread1 = new MyThread();  
MyThread myThread2 = new MyThread();  
myThread1.start();   //会创建新的线程
myThread2.start();  

       start方法是创建了新的线程,在新的线程中执行
       run方法是在主线程中执行该方法,和调用普通方法一样

2、实现Runnable接口

当前类如果已经继承一个父类,可以通过实现Runnable接口实现线程的创建

(1)线程类

public class MyThread extends A implements Runnable {

         public void run() {

            System.out.println("线程执行");  

(2)测试类

   MyThread s1=new MyThread();

   Thread t1 =new Thread(s1);

    t1.start();

}

3、实现Callable接口

(1)线程类

public class MyThread  extends OtherClass implements Callable<Integer> {
 
public Integer call() throws Exception {
      return 1;
 }

(2)测试类

Callable<Integer> oneCallable = new SomeCallable<Integer>();   
//由Callable<Integer>创建一个FutureTask<Integer>对象:   
FutureTask<Integer> oneTask = new FutureTask<Integer>(oneCallable);   
//FutureTask<Integer>是一个包装器,它通过接受Callable<Integer>来创建,它同时实现了Future和Runnable接口。    
Thread oneThread = new Thread(oneTask);   
oneThread.start();     
   
4、 newCachedThreadPool线程池

(1)匿名类方式

      ExecuteService  a=Executors.newCachedThreadPool();
              a.execute(new Runnable(){
                        public void run(){
                                 System.out.println("一个线程");

                       }
              });

(2)普通类方式

测试类

          ExecutorService service = Executors.newFixedThreadPool(2);//包含2个线程对象

         MyRunnable r = new MyRunnable();
         service.submit(r);

线程类

public class MyRunnable implements Runnable {
    public void run() {
           System.out.println("一个线程");    
    }    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值