Java线程简单调用

来源:互联网 发布:喀秋莎录屏软件破解版 编辑:程序博客网 时间:2024/06/05 06:01

实现接口:
接口:Runnable
重写方法:run()

调用方式:obj.run();

public class MutilThreadRunable implements Runnable {private String threadName;private int count;public MutilThreadRunable(String threadName, int count) {this.threadName = threadName;this.count = count;}@Overridepublic void run() {while (count < 20) {System.out.println(this.threadName);count++;try {Thread.sleep(1000);} catch (Exception e) {e.printStackTrace();}}}public String getThreadName() {return threadName;}public void setThreadName(String threadName) {this.threadName = threadName;}public int getCount() {return count;}public void setCount(int count) {this.count = count;}}

public static void main(String[] args) {MutilThreadRunable mtr0 = new MutilThreadRunable("王五", 15);MutilThreadRunable mtr1 = new MutilThreadRunable("赵六", 15);mtr0.run();mtr1.run();}


继承线程类
类名:Thread
重写方法:run()

调用方法:obj.start()

public class MutilThread extends Thread {private String threadName;private int count;public MutilThread(String threadName, int count) {this.threadName = threadName;this.count = count;}@Overridepublic void run() {while (count < 5) {System.out.println(threadName);count++;try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}public String getThreadName() {return threadName;}public void setThreadName(String threadName) {this.threadName = threadName;}public int getCount() {return count;}public void setCount(int count) {this.count = count;}}

public static void main(String[] args) {MutilThread mt0 = new MutilThread("张三", 0);MutilThread mt1 = new MutilThread("李四", 0);mt0.start();mt1.start();}

Runnable接口代码:

public interface Runnable {    /**     * When an object implementing interface <code>Runnable</code> is used      * to create a thread, starting the thread causes the object's      * <code>run</code> method to be called in that separately executing      * thread.      * <p>     * The general contract of the method <code>run</code> is that it may      * take any action whatsoever.     *     * @see     java.lang.Thread#run()     */    public abstract void run();}

Thread类实现了Runnable接口。

public class Thread implements Runnable { ...}

一般来说,用接口的比较多一些,因为Java中一个类智能继承一次,但是可以实现多个接口。
这两种方式的调用方式也不同:
Runnable接口使用run()调用;
Thread类使用start()方法调用;

这两种实现方式不管是哪种,他们都包含了wait()方法,也包含notify()和notifyAll()方法;


1 0
原创粉丝点击