进程:一个时间允许运行的程序;
单进程,多进程;多进程是同一时间点,允许执行多个程序;轮流对资源进行抢占;
线程:在进程基础上划分的更小的程序单元:依赖于进程;线程启动速度比进程快很多,多线程高并发处理时,速率更高;
Java是多线程编程语言;
多线程实现:线程类,该类必须实现对象接口与继承相应的类,继承了java.lang.Thread的程序类即为线程的主体类;但必须复写Thread的run()主方法;
class Mythread extends Thread//线程主体类
{
private String title;
public Mythread(String title)
{
this.title=title;
}
@Override
public void run() {
for(int x=0;x<10;x++)
{
System.out.println(this.title+"运行,x="+x);
}
}
//多线程执行的功能应在run()方法中定义;
public class sum {
public static void main(String[] args) {
new Mythread("线程A").run();
new Mythread("线程B").run();
new Mythread("线程C").run();
}
}
如果直接使用实例化对象调用run()方法,造成的结果是三个对象顺序执行;因此,实现多线程,必须调用start方法启动多线程;
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();//抛出异常;该异常为RuntimeException子类;每个线程类对象只允许启动一次,若重复启动,则抛出异常
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
private native void start0();//只定义了方法,但未实现;关键字为native;
java程序执行过程中,考虑到不同层次开发需求,支持有本地操作系统函数,称为JNI(java native interface)技术;可以使用操作系统提供的底层函数,进行特殊处理;start0()即为这样的方法;由JVM根据不同的操作系统,控制操作系统底层函数,匹配start0()方法;
由于单继承局限
有第二种多线程主体定义:实现java.lang.Runnable接口,接口定义为:
class my implements Runnable{//线程主体类,实现Runnable接口
private String title;
public my(String title)
{
this.title=title;
}
@Override
public void run() {//线程主体方法
for(int x=0;x<10000;x++)
{
System.out.println(this.title+"运行,x="+x);
}
}
}
public class sum {
public static void main(String[] args) {
//实现多线程操作,必须在Thread类中,使用start方法实现;
//Thread构造方法中,有Thread(Runnable)方法
Thread mythread=new Thread(new my("线程A"));
Thread mythread1=new Thread(new my("线程B"));
Thread mythread2=new Thread(new my("线程C"));
mythread.start();
mythread1.start();
mythread2.start();
}
}
Thread与Runnable关系
Thread类实现Runnable接口,之前继承Thread时,覆写的同样是Runnable接口run();
实现Runnable接口子类的类实现核心业务:
逻辑关系为:
在Thread构造函数中,提供Runnable接口子类初始化Thread类,在Thread中:
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}//使用init方法初始化Thread类
//使用target属性保存Runnable
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc,
boolean inheritThreadLocals) {
this.target = target;
}
//使用target属性启动继承自Runnable的run函数,该run方法为my重新覆写的run方法,而不是Thread的run方法;
@Override
public void run() {
if (target != null) {
target.run();
}
}
run()方法负责处理核心业务(也可以称之为资源),创建一个实现Runnable接口的类my,覆写run()方法,实现核心业务;
使用Thread类,创建多个线程对象,共同操作my类,调用my中run()方法,实现对run()资源的抢占;
public class StruggleTicket implements Runnable{
private int ticket=100;
private String name;
StruggleTicket(String name)
{
this.name=name;
}
@Override
public void run() {
for(int i=0;i<1000;i++)
{
if(ticket>0){
System.out.println(name+"**"+this.ticket--);
}
}
}
//1000个人抢100张票
public static void main(String[] args) {
StruggleTicket exp=new StruggleTicket("station:");//exp表示资源
new Thread(exp).start();
new Thread(exp).start();
new Thread(exp).start();
}
}
Callable实现多线程
Runnable多线程实现,无法获取返回值。java.util,concurrent.Callable实现多线程。
V call()
throws Exception
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
class MyThread implements Callable<String>
{
@Override
public String call() throws Exception {
for(int x=0;x<10;x++)
{
System.out.println("线程执行"+x);
}
return "【线程执行完毕】";
}
}
public class ThreadDemo {
public static void main(String[] args) throws Exception{
FutureTask<String> lis=new FutureTask<>(new MyThread());
new Thread(lis).start();
System.out.println("【线程返回数据】"+lis.get());
}
}
//FutureTask类中,run()方法中调用了callable的call()方法;
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
//Runnable中没有返回值,只有一个run()方法;
//java.util.concurrent.Callable接口中的call方法,有返回值,显示线程运行状态
//但是都依赖于Thread中的start()方法实现多线程;
- 线程对象使用Thread进行封装,线程启动使用的是start(),但启动后,进入就绪状态,没有执行;
- 操作系统调度资源,当线程调度成功后,进去到运行状态run()方法,当线程执行一段时间后,让出资源,进入阻塞状态,随后重新回归到就绪状态;
- run()方法执行完毕后,线程主要任务结束,进入停止状态;