编程语言
首页 > 编程语言> > Java线程使用

Java线程使用

作者:互联网

Java中线程的使用

1.定义好了⼀个线程类之后,我们就可以通过该类来实例化对象,对象就可以描述⼀个线程。
2. 实例化该对象之后,必须通过调⽤start()来开启该线程,这样该线程才会和其他线程来抢占CPU资源,不能调⽤run()⽅法,调⽤run()相当于普通的实例对象⽅法调⽤,并不是多线程。

package thread;

public class MyThread extends Thread {
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i = 0; i < 1000;i++) {
			System.out.println("-------------MyThread-----------");
		}
	}
}
package thread;

public class Test {
	public static void main(String[] args) {
		for(int i = 0; i < 1000;i++) {
			System.out.println("-----------------Test");
		}
		MyThread myThread = new MyThread();
		myThread.start();
	}
}

MyRunnable的使⽤与MyThread略有不同, MyRunnable相当于定义了线程的业务逻辑,但是它本身不是⼀个线程,所以需要实例化Thread类的对象作为线程,然后将MyRunnable对象赋给Thread对象,这样Thread就拥有了MyRunnable中定义的业务逻辑,再通过调⽤Thread对象的start⽅法来启动线程。

package thread;

public class MyRunnable implements Runnable {

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i = 0; i < 1000;i++) {
			System.out.println("!===Runnable===!");
		}
	}

}
package thread;

public class Test2 {
	public static void main(String[] args) {
		MyRunnable myRunnable = new MyRunnable();
		Thread thread = new Thread(myRunnable);
		thread.start();
		MyThread myThread = new MyThread();
		myThread.start();
	}
}

线程的状态

线程共有5种状态,在特定的情况下,线程可以在不同的状态之间完成切换,5种状态如下所示。

MyThread myThread = new MyThread();
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
myThread.start();
thread.start();

在这里插入图片描述


回到多线程目录

标签:MyRunnable,Java,thread,Thread,MyThread,线程,使用,public
来源: https://blog.csdn.net/qq_43776742/article/details/96473616