A Simple Goroutine Like Java Implementation

Posted by Yan on February 27, 2015

One of the greatest aspect of golang is that it is easy to do concurrent thing by using goroutine. In Java, when we want to start a thread, we have to define a class and implements the relative method. Here is a simple implementation in Java which can simplify the concurrent process:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.learnconcurrent;

/**
 * Created by daiyan on 27/02/15.
 */
public class MultiThread
{
    private class FuncThread implements Runnable
    {

        private Func func;

        FuncThread(Func func)
        {
            this.func = func;
        }

        @Override
        public void run()
        {
            func.func();
        }


        void start()
        {
            new Thread(new FuncThread(func)).start();
        }

    }

    private abstract class Func
    {

        abstract void func();
    }

    private void foo()
    {
        new FuncThread(new Func()
        {
        	// you can implement your own method
            @Override
            void func()
            {
                System.out.println("print a foo");
            }
        }).start();
    }

    public static void main(String[] args)
    {
        new MultiThread().foo();
    }

}

At line 40, we can simply start a thread. This implementation can be similar with those implemenation that are trying bring Functional Programming into Java.

gopherswrench