线程

一.多线程

1.基本概念

进程:正在运行中的程序,一个进程中至少包含一个线程

线程:进程的任务,执行任务的一个通道,一个进程中可以包含多个线程

2.多线程执行的特点:

两种方式:分时调度/抢占式调度(java属于抢占)

二.Thread 类(java.lang)

1.概述:使用该类表示多线程对象,只要创建一个Thread对象,就是一个线程对象产生了

2.定义:public class Thread extends Object implements Runnable

3.构造方法:

Thread():分配新的 Thread 对象

Thread(String name):使用指定的名称分配新的 Thread 对象

Thread(Runnable target):接收Runnable接口子类对象,实例化Thread对象

Thread(Runnable target, String name):接收Runnable接口子类对象,实例化Thread对象,并设置线程名称

4.常用方法:

public void run(){}:如果该线程是使用独立的 Runnable 运行对象构造的,则调用该 Runnable 对象的 run 

方法;否则,该方法不执行任何操作并返回。<所以该方法应自觉重写!!!>

public void start(){}:使该线程开始执行;Java 虚拟机调用该线程的 run 方法

public static Thread currentThread(){}:返回目前正在执行的线程

public final String getName(){}:返回线程的名称

public final int getPriority(){}:返回线程优先级

public final void setName(String name){}:设定线程名称

public final void setPriority(int newPriority){}:设定线程的优先值

public static void sleep(long millis) throws InterruptedException{}:使当前线程休眠多少毫秒

public static void yield(){}:将目前执行的线程暂停,允许其它线程执行

public final ThreadGroup getThreadGroup(){}:Returns the thread group to which this thread belongs. 

This method returns null if this thread has died (been stopped).

代码演示:

//多线程基本练习-Thread类
class MyThread extends Thread{
//重写run()
@Override
public void run(){
for(int i = 0; i < 100; i++){
System.out.println(Thread.currentThread()+"Jack"+i);
}
}
}
public class ThreadDemo{
public static void main(String[] args){
//创建一个线程
MyThread my = new MyThread();
//启动线程
my.start();
//主线程执行如下任务
for(int i = 0; i<100; i++){
System.out.println(Thread.currentThread()+"肉丝"+i);
}
//返回当前运行的线程名称
String s = my.getName();
System.out.println("当前线程名称为:"+s);//Thread-0
//修改线程名称
my.setName("Smith--");
System.out.println("修改后-当前线程名称为:"+my.getName());
//返回线程优先级
int i = my.getPriority();
System.out.println("当前线程优先级为:"+i);//5
}
}

三.Runnable 接口(java.lang)

1.概述:Runnable接口只有一个方法,run方法,因此实现Runnable接口的类,必须重写run方法,否则,语法报错;

2.实现接口的好处:

实现类可以继承其他类,不占用继承的位置;

可以多实现,可以将编写线程类和写任务代码的工作分离开;

3.定义:

@FunctionalInterface

public interface Runnable

4.方法:

public void run() 使用实现接口 Runnable 的对象创建一个线程时,启动该线程将导致在独立执行的线程中调用对象的 run 方法

代码演示:

//通过Runnable接口实现多线程
class MyRunnable implements Runnable{
@Override
public void run(){
for(int i = 0; i<100; i++){
System.out.println("Smith----------"+i+Thread.currentThread());
}
}
}
public class RunnableDemo{
public static void main(String[] args){
MyRunnable my = new MyRunnable();
Thread myThread = new Thread(my,"smith");
myThread.start();
//返回当前线程名称
System.out.println("当前线程:"+Thread.currentThread());
for(int i = 0;i<100;i++){
System.out.println("格林:==="+i+Thread.currentThread());
}
}
}


四.线程安全问题

原因:当多个线程使用共享的资源时,容易发生数据安全的问题;

解决方案:

Java 提供了3种解决安全问题的方式;

1:同步代码块

2:同步方法

3:Lock接口

1.同步代码块

/*使用3个线程,模拟3个窗口,卖100张票;
要求每个线程卖出去的票,不能重复且不能是无效票;
使用一个变量表示100张票,每个窗口卖出去一张票,就将该变量的值减一,直到0为止;
使用同步代码块
*/
class MyRunnable implements Runnable{
int ticket = 100;//总票数,只能new一次该类,因为每创建一次对象就会有100张票
@Override
public void run(){
String name = Thread.currentThread().getName();//获取当前线程名
while(true){
synchronized(this){
if(ticket<=0){
break;
}else{
System.out.println(name+"卖出第"+ticket+"号票");
ticket--;
}
}
}
}
}
public class SellTicket{
public static void main(String[] args){
//创建任务对象
MyRunnable my = new MyRunnable();
//创建线程
Thread t1 = new Thread(my,"窗口1");
Thread t2 = new Thread(my,"窗口2");
Thread t3 = new Thread(my,"窗口3");
//开启线程
t1.start();
t2.start();
t3.start();
}
}


2.同步方法

class MyRunnable implements Runnable{
//定义总票数为成员变量
int ticket = 100;
String name;
@Override
public void run(){
name = Thread.currentThread().getName();
//卖票任务
while(true){
sell();
if(ticket<=0){
break;
}
}
}
//同步方法
public synchronized void sell(){
if(ticket > 0){
System.out.println(name+"卖出第"+ticket+"号票");
ticket--;
}
}
}
public class SellTicket01{
public static void main(String[] args){
//创建任务对象
MyRunnable my = new MyRunnable();
//创建多线程
Thread t1 = new Thread(my,"窗口1");
Thread t2 = new Thread(my,"窗口2");
Thread t3 = new Thread(my,"窗口3");
//开启多线程
t1.start();
t2.start();
t3.start();
}
}

3.Lock接口

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class MyRunnable implements Runnable{
//定义票数为成员变量
int ticket = 100;
//创建锁对象
private static final Lock lock = new ReentrantLock();
@Override
public void run(){
String name = Thread.currentThread().getName();
while(true){
lock.lock();
try{
if(ticket > 0){
System.out.println(name+"卖出了第"+ticket+"号票");
ticket--;
}else{
break;
}
}finally{
lock.unlock();
}
}
}
}
public class SellTicket02{
public static void main(String[] args){
//创建任务对象
MyRunnable my = new MyRunnable();
//创建多线程
Thread t1 = new Thread(my,"窗口1");
Thread t2 = new Thread(my,"窗口2");
Thread t3 = new Thread(my,"窗口3");
//开启多线程
t1.start();
t2.start();
t3.start();
}
}


五.使用匿名内部类实现多线程

/*编写程序,创建两个线程对象,一根线程循环输出“播放背景音乐”,另一根线程循环输出
“显示画面”,要求线程实现Runnable接口,且使用匿名内部类实现*/
public class ThreadDemo003{
public static void main(String[] args){
new Thread(new Runnable(){
@Override
public void run(){
for(int i = 0; i < 100; i++){
System.out.println("播放背景音乐");
}
}
}).start();
new Thread(new Runnable(){
@Override
public void run(){
for(int i = 0; i <100; i++){
System.out.println("显示画面");
}
}
}).start();
}
}


/*编写程序,创建两个线程对象,一根线程循环输出“播放背景音乐”,另一根线程循环输出
“显示画面”,要求使用Thread类,且使用匿名内部类实现*/
public  class ThreadDemo03{
public static void main(String[] args){
new Thread(){
@Override
public void run(){
for(int i = 0; i<100; i++){
System.out.println("播放背景音乐");
}
}
}.start();
new Thread(){
@Override
public void run(){
for(int i = 0; i<100; i++){
System.out.println("显示画面");
}
}
}.start();
}
}


六.ThreadGroup 类(java.lang)

简介:线程组:java允许对一批线程进行管理,使用ThreadGroup表示线程组,所有线程均有指定线程组,如果没有显式指定,则为默认线程组.默认情况下,子线程和创建他的父线程

属于同一线程组.一旦某线程加入指定线程组内,该线程会一直属于该组,直至死亡,运行过程中不可改变.

继承关系:java.lang.Object--java.lang.ThreadGroup

定义:public class ThreadGroup extends Object implements Thread.UncaughtExceptionHandler

构造器:

ThreadGroup(String name): Constructs a new thread group.

ThreadGroup(ThreadGroup parent, String name): Creates a new thread group.

常用方法:

public int activeCount(){}:Returns an estimate of the number of active threads in this thread group and its subgroups

public int activeGroupCount(){}:Returns an estimate of the number of active groups in this thread group and its subgroups. 

Recursively iterates over all subgroups in this thread group.

public final void checkAccess() Throws SecurityException{}:Determines if the currently running thread has permission to modify this thread group.

public int enumerate(Thread[] list) Throws SecurityException{}:

public int enumerate(Thread[] list,boolean recurse)Throws SecurityException{}:Copies into the specified array every active thread 

in this thread group. If recurse is true, this method recursively enumerates all subgroups of 

this thread group and references to every active thread in these subgroups are also included. 

If the array is too short to hold all the threads, the extra threads are silently ignored.

public final String getName(){}:Returns the name of this thread group.

public final ThreadGroup getParent()Throws SecurityException{}:Returns the parent of this thread group.

public final boolean isDaemon(){}:Tests if this thread group is a daemon thread group

public final void setDaemon(boolean daemon)Throws SecurityException{}:Changes the daemon status of this thread group.

代码演示:获取当前系统内运行的所有线程组及线程名

import java.util.List;
import java.util.ArrayList;
public class ThreadListDemo{
public static void main(String[] args){
for(String s : getThreadGroups(getRootThreadGroups())){
System.out.println(s);
}
}
//getRootThreadGroups()
public static ThreadGroup getRootThreadGroups(){
//get current threadgroup
ThreadGroup rootGroup = Thread.currentThread().getThreadGroup();
while(true){
if(rootGroup.getParent() != null){
rootGroup = rootGroup.getParent();
}else{
break;
}
}
return rootGroup;
}
//getThreadGroups()传入一个线程组,获取该组内所有子线程组
public static  List<String> getThreadGroups(ThreadGroup group){
List<String> threadList = getThreads(group);//存子线程组名,调用getThreads方法,返回线程组内所有线程名
ThreadGroup[] groups = new ThreadGroup[group.activeGroupCount()];//活动的线程组名
int count = group.enumerate(groups,false);//复制子线程组到线程组数据,不递归复制
for(int i = 0; i< count; i++){
threadList.addAll(getThreads(groups[i]));
}
return threadList;
}
//传入一个线程组,返回该组内所有线程名
public static List<String> getThreads(ThreadGroup group){
List<String> threadList = new ArrayList<>();//存线程名
Thread[] list = new Thread[group.activeCount()];//活动线程
int count = group.enumerate(list,false);//复制当前进程到list中
for(int i = 0; i< count; i++){
threadList.add("名为:"+group.getName()+"的线程组,线程名为:"+list[i].getName());
}
return threadList;
}
}


七.Executor 接口(java.io.concurrent)

简介:线程池:由于线程涉及到与操作系统交互,所以启动一个新线程的成本比较高,因此,java提供了线程池机制来提高性能,尤其是当程序中需要大量生存期很短暂的线程时,应该考虑

使用线程池.所谓线程池是指在系统启动时即创建大量空闲的线程,程序将一个Runnable对象或Callable对象传给线程池,线程池就会启动一个线程来执行他们的run或call方法,当方法

结束时,线程并不会死亡,而是返回线程池成为空闲状态,等待执行下一个任务

定义: public interface Executor

方法:public void execute(Runnable command) Throws RejectedExecutionException | NullPointerException {}:Executes the given command at some time in the future

实现类:AbstractExecutorService, ForkJoinPool, ScheduledThreadPoolExecutor, ThreadPoolExecutor

子接口:ExecutorService, ScheduledExecutorService


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章