多线程的创建,方式一: 继承Thread类
1.创建一个继承Thread类的子类
2.重写Thread类的run()–>将此线程的操作声明在run()中
3.创建Thread类的子类的对象
4.通过此对象调用start()
例子:遍历100以内的所有的偶数
//1.创建一个继承Thread类的子类
class MyThread extends Thread{
//2.重写Thread类的run()
@Override
public void run() {
for (int i = 0; i <100 ; i++) {
if (i%2==0){
System.out.println(i);
}
}
}
}
public class ThreadTest {
public static void main(String[] args) {
//3.创建Thread类的子类的对象
MyThread myThread=new MyThread();
//4.通过对象调用start(): 1启动当前线程 2调用当前线程的run()
myThread.start();
//问题一:我们不能通过直接调用run()的方式启动线程
// myThread.run();
//问题二:再启动一个线程,遍历100以内的质数,不可以还让已经start()的程序执行。
//myThread.start();
//我们需要重新创建一个线程对象
MyThread myThread1=new MyThread();
myThread1.start();
//创建Thread类的匿名子类的方式
new Thread(){
@Override
public void run() {
for (int i = 0; i <100 ; i++) {
if (i%2==0){
System.out.println(Thread.currentThread().getName()+i+"****");
}
}
}
}.start();
//如下操作仍然是在main线程中执行的,
for (int i = 0; i <100 ; i++) {
if (i%2==0){
System.out.println(i+"****");
}
}
}
}
测试Thread中的常用方法
- 1.start():启动当前线程,调用当前线程run()
- 2.run():通常需要重写Thread类中的此方法,将创建的线程要执行操作声明在此方法中
- 3.currentThread():静态方法,返回执行当前代码的线程
- 4,getName():获取当前线程的名字
- 5.setName():设置当前线程的名字
- 6.yield():释放当前cpu的执行权
- 7.join():在线程A中调用线程B的join(),此时线程A就进入阻塞状态,直到线程B完全执行完以后,线程A 才结束阻塞状态
- 8.stop():已过时,当执行此方法时,强制结束当前进程
- 9.sleep(long millitime):让当前线程"睡眠"指定的millitime毫秒。在指定millitime毫秒时间内,当前线程是阻塞状态。
- 10.isAlive():判断当前线程是否存活
线程的优先级:
1.
MAX_PRIORITY:10
MIN_PRIORITY:1
NORM_PRIORITY:5 -->默认优先级
2.如何获取和设置当前线程的优先级:
getPriority():获取线程的优先级
setPriority(int p):设置线程的优先级
说明:高优先级的线程要抢占低优先级线程cpu的执行权。但是只是从概率上讲,高优先级的线程高概率的情况下被执行。并不意味着只有当高优先级的线程执行完以后,低优先级的线程才执行。
class HelloThread extends Thread{
@Override
public void run() {
for (int i = 0; i <100 ; i++) {
try{
sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+i+"****");
if (i%20==0){
yield();
}
}
}
}
public class ThreadMethodTest {
public static void main(String[] args) {
HelloThread helloThread = new HelloThread();
helloThread.setName("线程一");
//设置分线程的优先级
helloThread.setPriority(Thread.MAX_PRIORITY);
helloThread.start();
//给主线程命名
Thread.currentThread().setName("主线程");
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
for (int i = 0; i <100 ; i++) {
System.out.println(Thread.currentThread().getName()+i+"****");
if (i==20){
try{
helloThread.join();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}
创建多线程的方式二:实现Runnable接口
- 1.创建一个实现Runnable接口的类
- 2.实现类去实现Runnable中的抽象方法:Run()
- 3.创建实现类的对象
- 4.将此对象作为参数传递到Thread类的构造器中,创建Thread类对象
- 5.通过Thread类的对象调用Start()
比较创建线程的两种方式:
开发中:优先选择:实现Runnable接口的方式
原因:1.实现的方式没有类的单继承性的局限性
2.实现的方式更适合来处理多个线程有共享数据的情况。
- 联系:public class Thread implements Runnable
- 相同点:两种方式都需要重写run(),将线程要执行的逻辑声明在run()中。
//1.创建一个实现了Runnable接口的类
class MThread implements Runnable{
//2.实现类去实现Runnable中的抽象方法:Run()
@Override
public void run() {
for (int i = 0; i <100 ; i++) {
if (i%2==0){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
}
public class ThreadMethodTest2 {
public static void main(String[] args) {
//3.创建实现类的对象
MThread mThread = new MThread();
//4.将此对象作为参数传递到Thread类的构造器中,创建Thread类对象
Thread thread = new Thread(mThread);
thread.setName("线程1");
//5.通过Thread类的对象调用Start():1 启动线程 2调用当前线程的run()-->调用了Runnable类型的target的run()
thread.start();
//再启动一个线程,遍历100以内的偶数
Thread thread2 = new Thread(mThread);
thread2.setName("线程2");
thread2.start();
}
}
创建线程的方式三:实现Callable接口。 —JDK5.0新增
- 如何理解实现Callable接口的方式创建多线程比实现Runnable接口创建多线程方式强大?
- 1.call()可以有返回值的。
- 2.call()可以抛出异常,被外面的操作捕获,获取异常的信息。
- 3.Callable()是支持泛型。
//1.创建一个实现Callable的实现类
class NumThread implements Callable{
//2.实现call方法,将此线程需要执行的操作声明在call()中
@Override
public Object call() throws Exception {
int sum=0;
for (int i = 0; i <100 ; i++) {
if (i%2==0){
System.out.println(i);
sum+=i;
}
}
return sum;
}
}
public class ThreadMethodTest3 {
public static void main(String[] args) {
//3.创建Callable接口实现类的对象
NumThread numThread=new NumThread();
//4.将此Callable接口实现类的对象作为传递到FutureTask构造器中,创建FutureTask的对象
FutureTask futureTask = new FutureTask<>(numThread);
//5.将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start()
new Thread(futureTask).start();
try {
//6.获取Callable中call方法的返回值
//get()返回值即为FutureTask构造器参数Callable实现类重写的call()的返回值
Object sum = futureTask.get();
System.out.println("总和为"+sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
创建线程的方式四:使用线程池
好处:
1.提高响应速度(减少了创建新线程的时间)
2.降低了资源的消耗(重复利用线程中的线程,不需要每次都创建)
3.便于线程管理
corePoolSize:核心池的大小
maximumPoolSize:最大线程数
keepAliveTime: 线程没有任务时最多保持多长时间后会停止
class NumberThread implements Runnable{
@Override
public void run() {
for (int i = 0; i <=100 ; i++) {
if (i%2==0){
System.out.println(i);
}
}
}
}
class NumberThread1 implements Runnable{
@Override
public void run() {
for (int i = 0; i <=100 ; i++) {
if (i%2!=0){
System.out.println(i);
}
}
}
}
public class ThreadMethodTest4 {
public static void main(String[] args) {
//1.提供指定线程数量的线程池
ExecutorService executorService = Executors.newFixedThreadPool(10);
//设置线程池的属性
System.out.println(executorService.getClass());
//2.执行指定的线程的操作,需要提供实现Runnable接口或Callable接口实现类的对象
executorService.execute(new NumberThread());//适合使用于Runnable
executorService.execute(new NumberThread1());//适合使用于Runnable
//executorService.submit();//适合使用于Callable
//关闭连接池
executorService.shutdown();
}
}
创建三个窗口卖票,总票数为100张
存在线程的安全问题,待决解
在java中,我们通过同步机制,来解决线程的安全问题。
方式一:同步代码块
synchronized(同步监视器){
//需要被同步的代码
}
说明:1.操作共享数据的代码,即为需要被同步的代码
2.共享数据:多个线程共同操作的变量。比如:ticket就是共享数据
3.同步监视器,俗称:锁。任何一个类的对象,都可以充当锁
要求:多个线程必须要共用同一把锁。
补充:在实现Runnable接口创建多线程的方式中,慎用this充当同步监视器,可以考虑当前类充当同步监视器
方式二:同步方法
如果操作共享数据的代码完整的声明在一个方法中,我们不妨将此方法声明同步的
关于同步方法的总结:
1.同步方法仍然涉及到同步监视器,只是不需要我们显式的声明。
2.非静态的同步方法,同步监视器是:this
静态的同步方法,同步监视器是:当前类本身
class Window2 implements Runnable{
private int ticket=100;
Object obj=new Object();
@Override
public void run(){
while (true){
synchronized(obj){
if (ticket>0){
System.out.println(Thread.currentThread().getName()+":卖票,票号为:"+ticket);
ticket--;
}else {
break;
}
}
}
}
}
public class WindowTest2 {
public static void main(String[] args) {
Window t1=new Window();
Thread thread1 = new Thread(t1);
Thread thread2 = new Thread(t1);
Thread thread3 = new Thread(t1);
thread1.setName("窗口1");
thread2.setName("窗口2");
thread3.setName("窗口3");
thread1.start();
thread2.start();
thread3 .start();
}
}