创建
package com.day3.test;
/**
* User: Json
* Date: 2021/8/12
* 多线程创建方式一 继承Thread
* 1.创建一个继承于 thread类的字类
* 2. 重写thread类的run方法 --> 把你要创建的线程要做的事情 写再 run方法中
* 3. 创建thread类的子类对象
* 4.通过此对象调用start方法
**/
//1.创建一个继承于 thread类的字类
class myThread extends Thread {
// 2. 重写thread类的run方法
@Override
public void run() {
// super.run();
//Thread.currentThread().getName() 获取线程名称
for(int i=0;i<=100;i++){
if(i%2==0){
System.out.println(Thread.currentThread().getName()+"=>"+i);
}
}
}
}
public class ThreadTest{
public static void main(String[] args) {
//* 3. 创建thread类的子类对象 声明对象快捷键 atr+回车
myThread myThread = new myThread();
myThread.start();
//下面的这个for是主线程执行的
for(int i=0;i<=100;i++){
if(i%2==0){
System.out.println(i+"**** 我是主线程 跑的 数据");
}
}
//你会发现 主线程打印的数据 会穿插在线程里打印出来的数据中
// 因为现在 是两个线程同时在跑
//如果需要再启动一个线程 需要重新new一个对象
myThread myThread1 = new myThread();
myThread1.start();
}
}
线程练习
/**
* User: Json
* Date: 2021/8/12
* 创建两个分线程 一个遍历100 偶数 一个遍历 100奇数
**/
public class Demo {
public static void main(String[] args) {
my1 my1 = new my1();
my1.start();
my2 my2 = new my2();
my2.start();
//使用匿名类 创建 线程
new Thread(){
@Override
public void run() {
//super.run();
for(int i=0;i<=100;i++){
if(i%2==0){
System.out.println("匿名类===>"+Thread.currentThread().getName()+"=>"+i);
}
}
}
}.start();
}
}
//偶数
class my1 extends Thread{
@Override
public void run() {
// super.run();
for(int i=0;i<=100;i++){
if(i%2==0){
System.out.println("偶数===>"+Thread.currentThread().getName()+"=>"+i);
}
}
}
}
//奇数
class my2 extends Thread{
@Override
public void run() {
// super.run();
for(int i=0;i<=100;i++){
if(i%2!=0){
System.out.println("奇数===>"+Thread.currentThread().getName()+"=>"+i);
}
}
}
}
线程 thread 类 常用方法的使用
/**
* User: Json
* Date: 2021/8/12
* 练习 thread类中的方法
* 1. start() 启动当前线程
* 2. run() 线程具体要执行的东西
* 3. currentThread() 静态方法 返回当前代码的线程
* 4. getName() 获取当前线程名称
* 5. setName() 设置当前线程名称
* 6. yield() 释放当前cpu的执行权
* 7. join() 在线程A中 调用线程B的join方法 此时 线程A 就进入等待状态 直到线程B 执行完
* cpu 什么时候分配资源 才会继续执行线程A
* 8. stop() 停止 弃用了 强制结束
* 9. sleep(lang millitime) 休息一会 毫秒
* 10. isAlive() 判断当前线程是否还活着
**/
class my3 extends Thread{
//run() 线程具体要执行的东西
@Override
public void run() {
//super.run();
for(int i=0;i<=100;i++){
// currentThread() getName()
System.out.println(Thread.currentThread().getName()+i);
if(i%2 ==0){
// try {
//sleep
// sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
//yield()
// if(i%20==0){
// System.out.println("11111111111111111");
// this.yield();
// }
}
}
//方式二 修改线程名
public my3(String name){
//setName()
super(name);
}
}
public class ThreadMethodTest {
public static void main(String[] args) {
my3 my3 = new my3("json线程一 ==>");
//方式一 修改线程名 setName()
// my3.setName("json线程一 ==> ");
// start() 启动当前线程
my3.start();
//主线程
for(int i=0;i<=100;i++){
if(i%2==0){
System.out.println("偶数===>"+Thread.currentThread().getName()+"=>"+i);
}
if(i==20){
try {
//join()
my3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println(my3.isAlive());
}
}