JAVA编程思想——多线程

本文详细介绍了Java中多线程的基本概念和创建方法,包括直接继承Thread类、实现Runnable接口以及使用Callable和FutureTask的方式。通过实例演示了线程的启动和执行流程,适合初学者快速掌握Java多线程编程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

多线程

学习的同时,记录一下笔记,以后还会更新。

多线程简单例子入门
先看的这个,才看书。

线程的定义

在OS的定义中,进程是最小的资源分配单元,换句话说,进程是资源的占有者,如I/O,CPU等。一个进程包含一个或多个线程,线程是程序执行流的最小单元,或者说是最小的CPU调度单元,通俗的说,线程是实际的执行者。
线程共享进程的内存、寄存器等。

JAVA中几种线程的创建、阻塞

线程创建的几种方式:
  1. 直接继承自Thread类
public class TestThread {
	
	public static void main(String[] args) throws InterruptedException {
        Thread thread = new Mythread();
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
            if (i == 30) {
        		thread.start();
            }
        }
    }
}

public class Mythread extends Thread{
	@Override
	public void run() {
	    System.out.println("in Mythread run");
		for (i = 0; i < 100; i++) {
		    System.out.println(Thread.currentThread().getName() + " " + i);
		}
	}
}
  1. 重写Runnable接口
public class TestThread {
	
	public static void main(String[] args) throws InterruptedException {
		Runnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
            if (i == 30) {
        		thread.start();
            }
        }
    }
}

public class MyRunnable implements Runnable{

	private int i = 0;
	
    @Override
    public void run() {
        System.out.println("in MyRunnable run");
        for (i = 0; i < 100; i++) {
            System.out.println("runnable"+Thread.currentThread().getName() + " " + i);
        }
    }
}
  1. Callable和FutureTask
public class MyCallable implements Callable<Integer> {
	
	private int i = 0;

	@Override
	public Integer call() throws Exception {
		int sum = 0;
		for(;i<100;i++){
			System.out.println(Thread.currentThread().getName() + " " + i);
			sum += i;
		}
		return sum;
	}
	
}



import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Calltest {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		
		Callable<Integer> myCallable = new MyCallable();
		FutureTask<Integer> ft = new FutureTask<Integer>(myCallable);
		
		for(int i = 0;i<100;i++){
			System.out.println(Thread.currentThread().getName() + " " + i);
			if(i == 30){
				Thread thread = new Thread(ft);
				thread.start();
			}
			
		}
		System.out.println("线程执行完毕");
		
		int sum = ft.get();
		System.out.println("sum = " + sum);
	}

}

JAVA线程状态的流转

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值