Java多线程实现

Java中三种多线程的实现方式。

 

如果要想在Java中实现多线程有两种途径:

         ·继承Thread类;

         ·实现Runnable接口(Callable接口);

继承Thread

package thread;
//线程操作主类
class MyThread extends Thread//这是一个多线程的操作类
{
	private String name ;
	public MyThread(String name)
	{
		this.name = name;
	}
	@Override
	public void run() {//覆写run()方法,作为线程的主体操作方法
		for(int x = 1 ; x < 51 ; x++)
		{
			System.out.println(this.name + "-->"+x);
		}
	}
}
public class ThreadTest 
{
	public static void main(String[] args) 
	{
		MyThread mt1 = new MyThread("线程A");
		MyThread mt2 = new MyThread("线程B");
		MyThread mt3 = new MyThread("线程C");
		
		mt1.start();
		mt2.start();
		mt3.start();
	}
}

结果

线程A-->42
线程A-->43
线程A-->44
线程A-->45
线程A-->46
线程B-->1
线程A-->47
线程B-->2
线程A-->48
线程B-->3
线程A-->49
线程B-->4
线程C-->1
线程C-->2
线程A-->50
线程C-->3
线程C-->4
线程C-->5

疑问?为什么多线程启动不是调用run()方法而是调用start()方法?

看下strat方法定义

public synchronized void start() {
        if (threadStatus != 0)
            throw new IllegalThreadStateException();//线程多次调用时抛出异常
        group.add(this);
        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
            }
        }
}
private native void start0();

    发现在strat方法里面调用了start0()方法,与抽象方法类似,但是使用了native声明。在Java里有JNI技术(Java Native Interface),特点:使用Java调用本机操作系统提供的函数。缺点是不能够离开特定的操作系统。

    如果要想线程能够执行,需要操作系统来进行资源分配,所以操作严格来讲主要是由JVM负责根据不同的操作系统而实现的 。

   即:使用Thread类的start()方法不仅仅要启动多线程的执行代码,还要去根据不同的操作系统进行资源的分配。

猜你喜欢

转载自blog.csdn.net/qq_32965187/article/details/80854485