Java 多线程 创建 Thread Runnable
一、Thread
1、继承Thread
2、重写run方法(线体替)
3、实例化创建的线程类
4、运行 对象.start()
5、其他方法
a、获取/设置线程名
// 获取线程名 Thread.currentThread().getName()
设置
对象.setName(String类型)
b、线程休眠
Thread.sleep(Long类型)
c、设置/获取优先级(基本上没效果)
thread2.setPriority(10);
c、设置守护线程
// 守护线程 thread2.setDaemon(true);
6、案例
package com.wt.thread; public class Demon01Thread extends Thread { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName()+":执行线程..."+i); try { Thread.sleep(1L); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }
package com.wt.thread; public class Demon01 { public static void main(String[] args) { Demon01Thread thread1 = new Demon01Thread(); // 设置线程名 thread1.setName("西门"); // 设置优先级 thread1.setPriority(1); thread1.start(); Demon01Thread thread2 = new Demon01Thread(); thread2.setName("东方"); thread2.setPriority(10); // 守护线程 thread2.setDaemon(true); thread2.start(); for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName()+":执行主线程"+i); } } }
二、Runnable
1、定义类实现 Runnable
2、重写run方法(逻辑)
3、实例化 定义类
4、Thread thread = new Thread(实例化定义的类)
5、开启线程 thread.start()
package com.wt.thread; public class Demon02Run implements Runnable{ @Override public void run() { for (int i = 0; i < 20; i++) { System.out.println(Thread.currentThread().getName()+"执行线程"+i); } } }
package com.wt.thread; public class Demon02Thread extends Thread { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName()+"执行线程"+i); } } }
package com.wt.thread; public class Demon02 { public static void main(String[] args) { Demon01Thread thread = new Demon01Thread(); // 设置线程名 thread.setName("A"); // 设置守护线程 thread.setDaemon(true); // 开启线程 thread.start(); Demon02Run demon02Run = new Demon02Run(); Thread thread1 = new Thread(demon02Run); thread1.setName("B"); thread1.start(); } }
三、匿名内部类
package com.wt.thread; public class Demon03 { public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName()+"执行线程"+i); } } }, "test").start(); for (int i = 0; i < 20; i++) { System.out.println(Thread.currentThread().getName()+"执行"+i); } } }