线程入门

 public class NoThread1 {

    /**
     * @param args
     */
    int threadNumber;
    
    public NoThread1(int i) {
        System.out.println("Making thread= " + i);
        threadNumber = i;
    }
    
    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println("Running thread number=" + threadNumber);
        }
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new NoThread1(1).run();
        new NoThread1(2).run();
        System.out.println("End of main.");

    }

}

程序中调用了两次run方法,前一个run方法不执行完,下一个绝对不会抢着执行。

如果希望对程序中的某个方法(例如run方法)的两次或者多次调用能够同时进行,要进行下面的步骤:

1. 使该方法所在类继承Java中的Thread类;

2. 把该方法更名为run方法,run方法是Thread类中提供的一个方法。即:把希望并行处理的代码都放在run方法中。

3. 创建几个类的对象,并且用这些类的对象调用Thread类的start方法。start方法是Thread类定义的方法,它会调用run方法。

 

public class Thread1 extends Thread {

    /**
     * @param args
     */
    int threadNumber;
    public Thread1(int i) {
        System.out.println("Making thread=" + i);
        threadNumber = i;
    }
   
    public void run() {
        for(int i = 0; i < 3; i ++) {
            System.out.println("Running threadnumber = " + threadNumber);
        }
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new Thread1(1).start();
        new Thread1(2).start();
        System.out.println("End of main");
    }

}

 

如果多线程在一个类中实现,这个类也叫线程类(因为它继承了Thread类),这个类的不同对象调用run方法,会产生几个可并行运行的线程。

 

如果有多个线程类,Java的内在机制会自动使一个线程暂停运行,把处理器的时间让出来以便其他线程运行,处理器的时间就在线程之间不停地切换,最后的结果是所有线程都执行完毕。

 

class Thread2a extends Thread {

    /**
     * @param args
     */
    private int threadNumber;
   
    public Thread2a(int i) {
        System.out.println("Making thread 1=" + i);
        threadNumber = i;
    }
   
    public void run() {
        for(int i = 0; i < 2; i++) {
            System.out.println("Running thread 1 number =" + threadNumber);
        }
    }
    /*
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }
    */
}

class Thread2b extends Thread {
    private int threadNumber;
    public Thread2b(int i){
        System.out.println("Making thread 1=" + i);
        threadNumber = i;
    }
   
    public void run() {
        for(int i = 0; i < 2; i++) {
            System.out.println("Running thread 1 number =" + threadNumber);
        }
    }
}

public class Thread1a {
    public static void main(String[] args) {
        new Thread2a(1).start();
        new Thread2a(2).start();
        new Thread2b(2).start();
        new Thread2b(1).start();
        System.out.println("End of main.");

    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值