当前位置: 代码迷 >> 综合 >> 多线程的俩种简单实现方法(Multithreading)
  详细解决方案

多线程的俩种简单实现方法(Multithreading)

热度:6   发布时间:2023-11-07 07:45:11.0

      多线程实现有俩种方法(仅限于我这个初学多线程的娃):

                                                                                            ①继承自Thread类的类对象; 

                                                                                           ②实现于Runnable接口的类对象。

 

      二者的区别是:Thread:   一个Mythread(继承他的类对象)代表一个线程,故Mythread里面的资源不可共享;

                                Runnable: Thread修饰MyRunnable,一个Thread代表一个线程,故同一个MyRunnable里面的资源可共享。

 

public class RunnableandThreadDemo {public static void main(String[] args) {System.out.println("                   我们先使用继承Tread类的三个MyThread对象线程运行。\n\n");saleticketsTread();try {Thread.sleep(2000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("\n                               现在主线程休眠二秒... ...\n");System.out.println("\n现在采用实现Runnable接口的MyRunnable(Thread修饰)的三个接口(共享一个MyRunnable对象,从而实现了资源共享)....\n");saleticketsRunnable();}public static void saleticketsTread() {Mythread my1 = new Mythread("1号Tread类型窗口");Mythread my2 = new Mythread("2号Tread类型窗口");Mythread my3 = new Mythread("3号Tread类型窗口");my1.start();my2.start();my3.start();}public static void saleticketsRunnable() {MyRunnable my = new MyRunnable(); // 实例化MyRunnale(Runnale接口)再用Thread装饰MyRunnable my2 = new MyRunnable();Thread thr1 = new Thread(my, "Thread装饰的Runnale壹号窗口");Thread thr2 = new Thread(my, "Thread装饰的Runnale二号窗口");Thread thr3 = new Thread(my, "Thread装饰的Runnale三号窗口");thr1.start();thr2.start();thr3.start();}}/**一个Mythread代表一个线程,故Mythread里面的资源不可共享**/
class Mythread extends Thread { // Mythread继承Thread类,覆写Run方法,不共享资源private int tickets = 3;private String windowname; // 需要自己写赋予线程名字public Mythread(String windowname) {super();this.windowname = windowname;}public void run() {for (int i = 0; i < 4; i++) {if (tickets > 0) {System.out.println(windowname + "正在卖第" + tickets-- + "张票");}}}}/**Thread修饰MyRunnable,一个Thread代表一个线程,故同一个MyRunnable里面的资源可共享**/
class MyRunnable implements Runnable {private int tickets = 3;@Overridepublic void run() {// TODO Auto-generated method stubfor (int i = 0; i < 4; i++) {if (tickets > 0) {System.out.println(Thread.currentThread().getName() + "正在卖第" + tickets-- + "张票");}}}}

下附线程常用的方法:  Thread.currentThead()  ->当前线程可加上 ".getname()"等方法。    (th为Thread的对象)  th.isAlive() ——>判断线程是否死亡。   Thread.sleep(ms)。   th.join()强制运行     th.ionterrupt()强制中断  th.stePriority(x)  x= (1,10)设置优先值 。。。可能不尽如人意。。。     th.yied() 暂时礼让,稍后恢复。