⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 program5.txt

📁 Java多线程机制的源码包括线程控制方法、多线程实现方法 、如何用接口来创建线程、输入输出流类、创建目录和删除文件
💻 TXT
📖 第 1 页 / 共 4 页
字号:
4.6 Java多线程机制
    
4.6.1基本概念

4.线程控制方法

public class Thread implements Runnable 
{
    public final static int MIN_PRIORITY;
    public final static int NORM_PRIORITY;
    public final static int MAX_PRIORITY;

    public Thread();
    public Thread(Runnable target);
    public Thread(ThreadGroup group, Runnable target);
    public Thread(String name);
    public Thread(ThreadGroup group, String name);
    public Thread(Runnable target, String name);
    public Thread(ThreadGroup group, Runnable target, String name);

    public void run();
    public synchronized native void start();
    public final void stop();
    public final synchronized void stop(Throwable o);
    public static native void yield();
    public static native void sleep(long millis) throws InterruptedException;
    public static void sleep(long millis, int nanos) throws InterruptedException
    public final void suspend();
    public final void resume();
    public final synchronized void join(long millis) throws InterruptedException;
    public final synchronized void join(long millis, int nanos)throws InterruptedException;
    public final void join() throws InterruptedException;
    public void interrupt();
    public static boolean interrupted();
    public boolean isInterrupted();
    public void destroy();
    public final native boolean isAlive();
    public final void setPriority(int newPriority);
    public final int getPriority();
    public final void setName(String name);
    public final String getName();
    public final ThreadGroup getThreadGroup();
    public static native Thread currentThread();
    public static int activeCount();
    public static int enumerate(Thread tarray[]);
    public native int countStackFrames();
    public static void dumpStack();
    public final void setDaemon(boolean on);
    public final boolean isDaemon();
    public void checkAccess();
    public String toString();
}

____________________________________________________________

4.6.2多线程实现方法 

 例1:下面程序演示如何用生成Thread子类的方法来创建新线程。
//Program Name: ThreadTest1.java
public class ThreadTest1 
{
    ThreadTest1() 
    {
        FirstThread first = new FirstThread();
        SecondThread second = new SecondThread();
        first.start();
        second.start();
    }
    public static void main(String[] args) 
    {
        new ThreadTest1();
    }
}

class FirstThread extends Thread 
{
    public void run() 
    {
        try 
        {
            System.out.println("First thread starts running.");
            for(int i=0; i<10; i++) 
            { 
                System.out.println("First " + i);
                sleep(1000);
            }
           System.out.println("First thread finishes running."); 
        } 
        catch (InterruptedException e) {} 
    }
} 

class SecondThread extends Thread 
{
    public void run() 
    {
        try 
        {
            System.out.println("\tSecond thread starts running.");
            for(int i=0; i<10; i++) 
            {
                System.out.println("\tSecond " + i);
                sleep(1000);
            }
            System.out.println("\tSecond thread finishes running.");
        } 
        catch (InterruptedException e) {} 
    }
} 

程序设计了两个线程FirstThread类和SecondThread类,它们都是Thread类 的子类覆盖了run()方法,在其中分别进行打印数值的工作。
除了这两个线程 外,还有一个线程在执行,就是启动类线程,称它为主线程,它负责生成另外 两个线程,再用start()方法启动这两个线程。
线程first和second启动后,并发执行。观察执行结果会发现两个线程交替打印数据,而不是一个线程完成了所有打印工作后,另一个线程才开始打印工作,这就是多线程的本质。 
提示:线程在调用Thread类方法sleep()睡眠时,有可能产生异常,要求 应用程序用try-catch捕获这个异常,如果不用try-catch,程序将出错。 

某次的运行结果:
First thread finishes running.
First 0
	Second thread starts running.
	Second 0
	Second 1
First 1
First 2
	Second 2
First 3
	Second 3
First 4
	Second 4
	Second 5
First 5
First 6
	Second 6
First 7
	Second 7
First 8
	Second 8
First 9
	Second 9
First thread finishes running.
	Second thread finishes


________________________________________________

  例2:下面程序演示如何用生成Thread子类的方法来创建新线程。

//Program Name: ThreadTest2.java
public class ThreadTest2 
{ 
    ThreadTest2() 
    { 
        FirstThread first = new FirstThread(); 
        SecondThread second = new SecondThread();
        first.start(); 
        second.start();
        try 
        { 
            first.join();
            System.out.println("Waiting for first thread to finish..."); 
            System.out.println("Waking up second thread...");
            second.resume();
        } 
        catch (InterruptedException e) {}
    }
    public static void main(String[] args) 
    {
        new ThreadTest2();
    }
}

class FirstThread extends Thread 
{
    public void run() 
    {
        try 
        {
            System.out.println("First thread STARTS running.");
            for(int i=0; i<10; i++) 
            { 
               System.out.println("First " + i); 
               sleep(1000); 
            } 
            System.out.println("First thread FINISHES running.");
        } 
        catch (InterruptedException e) {} 
    }
} 

class SecondThread extends Thread 
{
    public void run() 
    {
        try 
        { 
            System.out.println("\tSecond thread STARTS running."); 
            for(int i=0; i<10; i++) 
            {
                if(i== 4) 
                    suspend();
                System.out.println("\tSecond " + i);
                sleep(1000);
            }
            System.out.println("\tSecond thread FINISHES running.");
        } 
        catch (InterruptedException e) {}
    }
}

程序仍然使用两个线程打印数据,不同的是second线程在打印数据过程中,发现是数值4,则调用suspend()方法,暂停本身的执行。
主线程用join()方法等线程first执行结束后,用resume()方法来唤醒second线程,second线程被唤醒后,将继续完成打印工作。
提示:join()也将出现InterruptedException异常,所以必须捕获异常。

某次的运行结果:
First thread STARTS running.
First 0
	Second thread STARTS running.
	Second 0
First 1
	Second 1
First 2
	Second 2
First 3
	Second 3
First 4
First 5
First 6
First 7
First 8
First 9
First thread FINISHES running.
Waiting for first thread to finish...
Waking up second thread...
	Second 4
	Second 5
	Second 6
	Second 7
	Second 8
	Second 9
	Second FINISHES finishes

____________________________________________________________


例3:下面的程序说明如何用接口来创建线程。
 
 //Program Name: RunTest.java
public class RunTest 
{
    RunTest() 
    {
        FirstThread first = new FirstThread();
        SecondThread second = new SecondThread();
        Thread thread1 = new Thread(first);
        Thread thread2 = new Thread(second);
        thread1.start();
        thread2.start();
    }
    public static void main(String[] args) 
    {
        new RunTest();
    }
}

class FirstThread implements Runnable 
{
    public void run() 
    {
        try 
        {
            System.out.println("First thread starts running.");
            for(int i=0; i<10; i++) 
            { 
                System.out.println("First " + i);
                Thread.sleep(1000);
            }
            System.out.println("First thread finishes running."); 
        } 
        catch (InterruptedException e) {} 
    }
}        

class SecondThread implements Runnable 
{
    public void run() 
    {
        try 
        {
            System.out.println("\tSecond thread starts running.");
            for(int i=0; i<10; i++) 
            {
                System.out.println("\tSecond " + i);
                Thread.sleep(1000);
            }
            System.out.println("\tSecond thread finishes running.");
        } 
        catch (InterruptedException e) {} 
    }
} 

    这个程序与ThreadTest1.java有相同的功能,只不过现在用实现Runnable接口的方法来创建和执行线程。
   

______________________________________________
_____________________________________________


4.5 输入输出流类

4.5.1文件系统

1.文件路径和属性

例子:下面的程序首先判断给定文件是否存在,如果存在则显示文件路径、绝对路径等,然后再查询文件的属性。
 
//Program Name: FileTest1.java
import java.io.*;
class FileTest1 
{
    public static void main(String[] args) 
    {
        String path;
        if(args.length != 1) 
        {
            System.err.println("Usage: java FileTest1 File or Dir");
            System.exit(-1);
        }
        File f = new File(args[0]);
        if (f.exists()) 
        {
            System.out.println("----------------------------- ");
            System.out.println("Absolute Path:     " + f.getAbsolutePath());
            System.out.println("File Path:              " + f.getPath());
            System.out.println("File Name:            " + f.getName());
            System.out.println("Parent Dirtory:    " + f.getParent());
            System.out.println("----------------------------- ");
            String canRead = f.canRead()   ? "Yes" : "No";
            String canWrite = f.canWrite() ? "Yes" : "No";
            String isFile = f.isFile()     ? "Yes" : "No";
            String isDir = f.isDirectory() ? "Yes" : "No";
            String isAbs = f.isAbsolute()  ? "Yes" : "No";
            System.out.println("Readable:            "+canRead);
            System.out.println("Writable:             "+canWrite);
            System.out.println("Is directoty:         "+isDir);
            System.out.println("Is file:                   "+isFile);
            System.out.println("Is absolute path:  "+isAbs);
        }
        else System.out.println("Cannot found file: " + args[0]);
    }
}

这是一个Application程序,用命令行参数接受输入文件名。读者可以用不同的命令行参数来执行上面的程序,体会上述方法的区别。

运行:java FileTest1 c:\wjjava\filetest1
运行结果:
----------------------------- 
Absolute Path:   c:\wjjava\filetest1 
File Path:           c:\wjjava\filetest1
File Name:         filetest1
Parent Dirtory:   c:\wjjava
-----------------------------
Readable:        Yes 
Writable:          Yes
Is directoty:      Yes
Is file:               No
Is absolute path:Yes

—————

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -