经典问题:有多少种创建线程的方式?
回答四种。继承Thread类,实现Runnable接口,实现Callable接口,线程池。
一、线程的创建
1、继承Thread类
/*
多线程的创建:
①
继承于Thread类
重写run方法-->将此线程的操作声明在run中
建对象对象调用start方法
*/
class MyThread extends Thread{
@Override
public void run() {
for (int i=0;i<100;i++){
if(i%2==0){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
}
public class ThreadCreate {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();//启动当前线程+调用当前线程的run方法
//t1.start();// 且只能start一次
//t1.run(); //不会启动线程,仍在主线程上执行
MyThread t2 = new MyThread();
t2.start();
//在主线程中
for (int i=0;i<100;i++){
if(i%2==0){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
}
2、实现Runnable接口
/*
创建多线程的方式二:显示runnable接口
1、创建一个实现了runnable接口的类
2、实现类去实现runnable中的抽象方法:run()
3、创建实例对象
4、将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
5、通过Thread类的对象调用start
*/
//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 ThreadCreate2 {
public static void main(String[] args) {
//3、创建实例对象
MThread m = new MThread();
//4、将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
Thread t1 = new Thread(m);
//5、通过Thread类的对象调用start -->调用了Runnable类型的target的run()
t1.start();
//再启动一个线程
Thread t2 = new Thread(m);
t2.start();
Thread t3 = new Thread(m);
t3.start();
}
}
三、实现Callable接口
/* 创建线程的方式三
Callable接口
更强大之处:
1、call方法有返回值
2、call方法可以抛出异常
3、Callable支持泛型
*/
class Num implements Callable{
@Override
public Object call() throws Exception {
int sum=0;
for (int i = 1; i < 101; i++) {
if (i%2==0){
System.out.println(i);
sum+=i;
}
}
return sum;
}
}
public class CallableStudy {
public static void main(String[] args) {
Num n1 = new Num();
FutureTask futureTask = new FutureTask(n1);
Thread t1 = new Thread(futureTask);
t1.start();
try {
//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 pool1 implements Runnable{
@Override
public void run() {
for (int i = 0; i <=100; i++) {
if (i%2==0){
System.out.println(Thread.currentThread().getName()+i);
}
}
}
}
public class ThreadPool {
public static void main(String[] args) {
//1、提供指定线程数量的线程池
ExecutorService service = Executors.newFixedThreadPool(10);
ThreadPoolExecutor service1 = (ThreadPoolExecutor)service;
//设置线程池的属性
//System.out.println(service.getClass());
//service1.setCorePoolSize(20);//设置池的大小
//2、执行指定的线程的操作。需要提供实现Runna接口或Callable接口实现类对象
service.execute(new pool1());//适用于Runnable
//3、关闭线程池
service.shutdown();
// service.submit(Callable callable);//适合使用于Callable
}
}
二、线程的主要内容
1、设置线程的优先级
aThread a = new aThread();
//设置分线程的优先级
a.setPriority(Thread.MAX_PRIORITY);
2、线程的小函数
/* yield():释放当前cpu的执行权,重新争抢cpu join():先执行join中的进程 IsAlive():判断线程是否存在 sleep(long millitime):让当前线程睡眠~毫秒数 */
3、线程安全
1、懒汉式
/*
使用同步机制 将单例模式 中的 懒汉式 改写为线程安全问题
*/
public class BankTest {
public static void main(String[] args){
System.out.println("单例模式中的懒汉式线程安全问题");
}
}
class Bank{
private Bank(){}
private static Bank instance=null;
//private static synchronized Bank GetInstance(){
//加入synchronized后则变成同步方法 同步监视器为 Bank.class
private static Bank GetInstance(){
//方式一:效率稍差
// synchronized (Bank.class) {
// //与上述加入static的效果一致 c+a+t
// if (instance==null){
// instance=new Bank();
// }
// return instance;
// }
//方式二:
if(instance==null) {
synchronized (Bank.class) {
//与上述加入static的效果一致 c+a+t
if (instance == null) {
instance = new Bank();
}
}
}
return instance;
}
}
2、同步代码块
①实现Runnable接口
/*
三个窗口卖票。出现冲票错票都是错误
问题出现原因:当某个线程操纵车票途中,尚未操作完成时,其他线程参与进来,操作车票
解决方法:当线程a操作ticket的时候,其中的线程不能参与进来,直到线程a操作完成ticket时,
其他线程才可以操作ticket。即使a出现了阻碍但是也不能改变
通过同步机制解决安全问题
方式一:同步代码块
synchronized(同步监视器){
//需要被同步的代码
}
说明:1、操作共享数据的代码,即被同步的代码
2、共享数据:多个线程共同操作的变量
3、同步监视器 俗称:锁 任何一个类的对象,都可以充当锁
要求,多个线程必须共用一把锁
补充:实现Runnable接口出啊关键多线程的方式中,可使用this来作为锁
方式二:同步方法
共享数据的代码完整声明在同一个方法中,我们不妨此方法此方法声明为同步的
*/
class window1 implements Runnable{
private int tickets=100;
Object obj = new Object();
@Override
public void run() {
//Object obj = new Object(); //必须共用一把锁
while(true) {
synchronized(this){//synchronized(obj){
//this在本类中就是唯一对象 当前对象
if (tickets > 0) {
try {
Thread.sleep(100);//出现0票或者-1票 错票
//阻塞也不会出现进程被抢的状态
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + tickets);
tickets--;
} else {
break;
}
}
}
}
}
public class TicketsTS1 {
public static void main(String[] args) {
window1 w1=new window1();
Thread t1 = new Thread(w1);
t1.start();
Thread t2 = new Thread(w1);
t2.start();
Thread t3 = new Thread(w1);
t3.start();
}
}
②继承Thread类
/*
方式一:同步代码块
synchronized(同步监视器){
//需要被同步的代码
}
说明:1、操作共享数据的代码,即被同步的代码
2、共享数据:多个线程共同操作的变量
3、同步监视器 俗称:锁 任何一个类的对象,都可以充当锁
要求,多个线程必须共用一把锁
补充:在继承Thread类创建多线程的方式中,考虑使用当前类作为同步监视器
*/
class window2 extends Thread{
private static int ticket = 100;
private static Object obj = new Object();
@Override
public void run() {
//正确的
//synchronized (obj) {
//不可以使用当前对象 因为this代表着t1,t2,t3
synchronized(window2.class){//类也是对象 window2只会加载一次
while (true) {
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName() + "卖票,票号为:" + ticket);
ticket--;
} else {
break;
}
}
}
}
}
public class TicketsTS2 {
public static void main(String[] args) {
window2 w1 = new window2();
window2 w2 = new window2();
window2 w3 = new window2();
w1.setName("窗口1");
w2.setName("窗口2");
w3.setName("窗口3");
w1.start();
w2.start();
w3.start();
}
}
3、同步方法
1)同步方法仍然涉及到同步监视器,只是不需要我们显式的声明。
2)非静态的同步方法,同步监视器是:this 即对象本身
静态的同步方法,同步监视器是:当前类本身
①实现Runnable接口
/*
Runnable接口实现线程安全问题
方式二:同步方法
共享数据的代码完整声明在同一个方法中,我们不妨此方法此方法声明为同步的
*/
class window3 implements Runnable{
private int tickets=100;
Object obj = new Object();
@Override
public void run() {
//Object obj = new Object(); //必须共用一把锁
while (tickets>0) {
sold();
}
}
private synchronized void sold(){
//synchronized(this){
if (tickets > 0) {
try {
Thread.sleep(100);//出现0票或者-1票 错票
//阻塞也不会出现进程被抢的状态
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + tickets);
tickets--;
}
}
}
public class TicketsTS11 {
public static void main(String[] args) {
window3 w1=new window3();
Thread t1 = new Thread(w1);
t1.start();
Thread t2 = new Thread(w1);
t2.start();
Thread t3 = new Thread(w1);
t3.start();
}
}
②继承Thread类
/*
方式二:同步方法
同步方法与实现Runnable接口下实现的方法类似
但需要注意的是:
1、同步方法仍然涉及到同步监视器,只是不需要显式声明
2、非静态的同步方法,同步监视器是当前对象this
静态的同步方法,同步监视器是当前类本身 即window4.class
*/
class window4 extends Thread{
private static int ticket = 100;
@Override
public void run() {
while (ticket > 0) {
sold();
}
}
private static synchronized void sold(){//此同步监视器为 window4.class
//不加 static的话 相当于同步监视器有t1,t2,t3三个
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "卖票,票号为:" + ticket);
ticket--;
}
}
}
public class TicketsTS22 {
public static void main(String[] args) {
window4 w1 = new window4();
window4 w2 = new window4();
window4 w3 = new window4();
w1.setName("窗口1");
w2.setName("窗口2");
w3.setName("窗口3");
w1.start();
w2.start();
w3.start();
}
}
4、锁
/*
解决线程安全问题方式三:Lock锁
synchronized 与 lock的异同
同:二者都可以用于线程的安全问题
异:synchronized机制在执行完相应的同步代码以后,自动释放同步监视器
lock需要手动的启动同步,同时0需要手动实现解锁
*/
class window implements Runnable{
private int tickets=100;
//1、实例化一个Lock
private ReentrantLock lock=new ReentrantLock();//构造器c+p
//fair=true 轮次每个人来一次
@Override
public void run() {
while(true){
try{
//2、调用lock() 锁定
lock.lock();
if(tickets>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":售票"+tickets);
tickets--;
}else {
break;
}
}finally {
//3、解锁方法 ,unlock
lock.unlock();
}
}
}
}
public class LockMethodSafe {
public static void main(String[] args) {
window w1=new window();
Thread t1=new Thread(w1);
Thread t2=new Thread(w1);
Thread t3=new Thread(w1);
t1.start();
t2.start();
t3.start();
}
}
锁的练习(授课+自行实现)
/*
两个客户,同一个账户每人向账户存入3000元,每次一千
*/
import java.util.concurrent.locks.ReentrantLock;
//授课方法
class Account{
private double balance;
public Account(double balance) {
this.balance = balance;
}
//存钱
public synchronized void deposit(double amt){
//public void deposit(double amt){
if (amt>0) {
balance += amt;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"存钱成功!余额为:"+balance);
}
}
}
class Customer extends Thread{
private Account acc;
public Customer(Account acc) {
this.acc = acc;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
acc.deposit(1000);
}
}
}
//自行处理方式一
class BankCustomer implements Runnable {
private double balance=0;
public synchronized void deposit(double amt){
if (amt>0){
balance+=amt;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"余额:"+balance);
}
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
deposit(1000);
}
}
}
//自行处理方式二
class BankCr extends Thread{
private static double balance=0;
private static ReentrantLock lock = new ReentrantLock();
public void deposit(double amt){
if (amt>0){
balance+=amt;
System.out.println(Thread.currentThread().getName()+"余额:"+balance);
}
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
lock.lock();
deposit(1000);
lock.unlock();
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Pratice01 {
public static void main(String[] args) {
//教学方法
// Account acc=new Account(0);
// Customer c1=new Customer(acc);
// Customer c2=new Customer(acc);
//
// c1.start();
// c2.start();
//独自1
// BankCustomer b1 = new BankCustomer();
// Thread t1 = new Thread(b1);
// Thread t2 = new Thread(b1);
//
// t1.start();
// t2.start();
//独自2
BankCr b2=new BankCr();
BankCr b3=new BankCr();
b2.start();
b3.start();
}
}
5、线程通信问题(经典生产者于消费者问题)
*wait,notify,notifyall三种方法的使用
/*
wait,notify,notifyall三个方法必须使用在同步代码块或同步方法中
该三个方法的调用者是 同步代码块的同步监听器 及synchronized()中括号的内容
否则出现非法的motion错误
三种方法都定义在 java.Objcet类当中
*/
/*
sleep()和wait()方法异同?
1、相同点:一旦执行方法,都可以使当前进程进入阻塞状态
2、不同点:1)两个方法圣光明的位置不同:Thread类中声明sleep(),Object类中声明wait()
2)调用的范围不同:sleep()可以在任何场景使用,wait()必须使用在同步代码块中
3)关于是否释放同步监视器:若两方法都使用在同步代码块中,sleep()不释放同步监视器,wait()释放同步监视器
*/
class goods{
private int number;
public goods(int number) {
this.number = number;
}
public void product(){
number++;
System.out.println("生产商品!当前商品数量为:"+number);
}
public void consume(){
number--;
System.out.println("消费商品!当前商品数量为:"+number);
}
public int getNumber() {
return number;
}
}
//生产者
class productor extends Thread{
private goods gs;
public productor(goods gs) {
this.gs = gs;
}
@Override
public void run() {
while(true){
synchronized (gs) {
gs.notify();
gs.product();
if(gs.getNumber()>20){
try {
gs.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class cumstomer implements Runnable{
private goods gs;
public cumstomer(goods gs) {
this.gs = gs;
}
@Override
public void run() {
while(true){
synchronized (gs) {
gs.notify();
if(gs.getNumber()>0){
gs.consume();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
gs.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class Clerk {
private int num = 0;
public synchronized void produce() {
if (num < 20) {
num++;
System.out.println(Thread.currentThread().getName() + "开始生产第" + num + "个产品");
notify();
} else {
//等待
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void consume() {
if (num > 0) {
System.out.println(Thread.currentThread().getName() + "开始消费第" + num + "个产品");
num--;
notify();
}else{
//等待
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Producer extends Thread{
private Clerk clk;
public Producer(Clerk clk) {
this.clk = clk;
}
@Override
public void run() {
System.out.println(getName()+"开始生产....");
while(true){
try {
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
clk.produce();
}
}
}
class Consumer extends Thread{
private Clerk clk;
public Consumer(Clerk clk) {
this.clk = clk;
}
@Override
public void run() {
System.out.println(getName()+"开始消费....");
while(true){
try {
sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
clk.consume();
}
}
}
public class ProductorAndCustomer extends Thread{
public static void main(String[] args) {
//自行实现
// goods gs = new goods(0);
// productor p1 = new productor(gs);
// cumstomer c1 = new cumstomer(gs);
// Thread t1 = new Thread(c1);
// Thread t2 = new Thread(c1);
//
// p1.start();
// t1.start();
// t2.start();
//教程方法
Clerk clk = new Clerk();
Producer p1 = new Producer(clk);
Consumer c1 = new Consumer(clk);
Consumer c2 = new Consumer(clk);
p1.start();
c1.start();
c2.start();
}
}