java中实现多线程

本文介绍了Java中实现多线程的两种主要方法:通过继承Thread类和实现Runnable接口。此外,还提供了一个示例程序,展示如何让两个线程交替打印数字1到100。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java中实现多线程有两种方法:继承Thread类和实现Runable接口。(实际上Thread类实现了Runable接口)
当用户线程类仅仅继承Thread类,则选用第一种方法,然而当要继承多个类,则实现Runable接口。两种方法
的实现如下:

一、继承Thread类

//定义自己的线程类
class Mythread extends Thread
{
    
//重写Thread类中的Run函数,该类所有的功能均在Run函数中运行
    public void run()
    {
        
//............
    }
}
//使用该线程类
class ThreadDemo
{
    
public static void main(String[] args)
    {
        MyThread thread1
=new MyThread();
        MyThread thread2
=new MyThread();
        
//调用start函数启动该线程,该函数的功能是启动run方法
        thread1.start();
        thread2.start();
    }    
}

 

二、实现Runable接口

 

//定义自己的线程类
class MyThread implements Runnable
{

    
//实现Runable接口中的Run函数,该类所有的功能均在Run函数中运行
    public void run()
    {
        
//............
    }
}
//使用该线程类
class ThreadDemo
{
    
public static void main(String[] args)
    {
        Thread thread1
=new Thread(new MyThread());
        Thread thread2
=new Thread(new MyThread());
        
//调用start函数启动该线程,该函数的功能是启动run方法
        thread1.start();
        thread2.start();
    }    
}

 三、使用内类简化上述方法

public void oneMethod()
{
    Thread thread
=new Thread(new Runnable()        //这里的Runnable也可以换成Thread
    {
        
public void run() 
        {
            
//在这里添加运行代码....
            
//while(your boolVar)
            
//{
                
//.........
            
//}
        }

    });
    thread.start();
}

 下面的程序中,Test中的synchronized public void printNumber(int id)方法打印从1到100的数,其中id为调用该方法的线程的id,以表明是那个线程在调用该方法。方法中的代码实现了两个线程轮流打印10个数。具体代码如下:

 

public class MyThread implements Runnable
{
    
private Test instance;
    
private int id;
    MyThread(
int id,Test instance)
    {
        
this.id=id;
        
this.instance=instance;
    }
    
public void run()
    {
        instance.printNumber(id);
    }
}

 

public class Test
{
    
synchronized public void printNumber(int id)
    {
        
for(int i=1;i<=100;i++)
        {
            System.out.println(i
+"----"+id);
            
if(i%10==0)
            {
                
this.notify();
                
if(i!=100)
                {
                    
try
                    {
                        
this.wait();
                    }
                    
catch(Exception e)
                    {
                        System.out.println(e);
                    }
                }
            }
        }
    }
    
public static void main(String[] args)
    {
        Test test
=new Test();
        Thread thread1
=new Thread(new MyThread(1,test));
        Thread thread2
=new Thread(new MyThread(2,test));
        thread1.start();
        thread2.start();
    }
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值