Java线程

线程有多个操作状态:

线程的状态:准备好了一个多线程的对象
就绪状态:调用了start方法,等待CPU调度
运行状态:执行run()方法
阻塞状态:暂时停止执行,可能将资源交给其他线程使用
终止状态:线程销毁

一个进程可以包括多个线程。

在Java中,线程的实现有两种:
1、继承Thread类
2、实现Runnable接口
Thread类:继承Thread类必须重写run()方法。

 使用Thread类实现进程如下:

定义线程:

public class MyThread extends Thread {
	
	private String name;
	public MyThread(String name) {
		this.name=name;
	}
	public void run() {
		for (int i = 0; i < 1000; i++) {
			System.out.println(name+":"+i);
		}
		super.run();
	}
}

 用MyThread的start方法启动线程。

public class ThreadDemo01 {

	public static void main(String[] args) {
		MyThread t1=new MyThread("A");
		MyThread t2=new MyThread("B");
//		t1.run();
//		t2.run(); 
		//线程通过start方法启动
		t1.start();
		t2.start();
		
	}

}

使用Runnable接口实现线程:

接口的run方法在线程启动后自动执行。

public class MyRunable   implements Runnable{
	
	private String name;
	public MyRunable(String name) {
		this.name=name;
	}
	
	public void run() {
		for (int i = 0; i < 1000; i++) {
			System.out.println(name+":"+i);

		}
	}
}

 启动线程:因为Runnable并没有start方法,只能实例化Thread类来启动线程

public class ThreadDemo01 {

	public static void main(String[] args) {

		MyRunable r1=new MyRunable("A");
		MyRunable r2=new MyRunable("B");
		Thread t1=new Thread(r1);
		Thread t2=new Thread(r2);
		t1.start();
		t2.start();
	}
}

线程的常用方法:
1、取得线程名称:getName()
2、取得当前线程对象:currentThread()
3、判断线程是否启动:isAlive()
4、线程的强行运行:join()
5、线程的休眠:sleep()
6、线程的礼让:yield()

class RunnableDemo implements Runnable{
	
	private String name;
	
	public RunnableDemo(String name) {
		this.name=name;
	}
	public void run() {
		for (int i = 0; i <20; i++) {
//			try {
//				Thread.sleep(1000);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
			System.out.println(name+":"+i);
			if (i==10) {
				System.out.println("礼让另一个线程****************");
				Thread.yield();
				
			}
			
//			System.out.println("当前线程对象:"+Thread.currentThread().getName());
			
		}
	}
}
public class ThreadDemo02 {

	public static void main(String[] args) {
		RunnableDemo r=new RunnableDemo("A");
		RunnableDemo r2=new RunnableDemo("B");
		Thread t=new Thread(r);
		Thread t2=new Thread(r2);
//		System.out.println(t.isAlive());
		t.start();
		t2.start();
//		System.out.println(t.isAlive());
		
	}
}
原文地址:https://www.cnblogs.com/zhhy236400/p/10490510.html